如何确定是否任意URL定义路由匹配 [英] How to determine if an arbitrary URL matches a defined route

查看:191
本文介绍了如何确定是否任意URL定义路由匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何判断一个字符串特定命名路由匹配?

我有一个这样的路线:

  routes.MapRoute(
    FindYourNewRental
    发现 - 你的新租赁/ {市场} / {}社区的.html
    新{控制器=FindYourNewRental,行动=社区}
    );字符串的URL =htt​​p://www.website.com/find-your-new-rental/northerncalifornia/sacramento.html

我如何编程告诉如果URL的字符串,路由匹配?事情是这样的:

  //与指定路线FindYourNewRental匹配的网址
如果(IsRouteMatch(URL,FindYourNewRental))
{
    // 做一点事
}公共BOOL IsRouteMatch(URL字符串,字符串routeName)
{
     //我如何code这个功能
}


解决方案

我解决了这个通过添加创建一个新的HttpContext与所提供的网址和应用程序的路径,并使用它来获取基础上的RouteData实例的定制RouteInfo类新的HttpContext对象。那么我可以评估控制器和动作值,看看哪条路线被匹配。我有这样的接线对Uri类的扩展方法。这感觉有点hackish,我希望有一个更清洁的方式做到这一点,所以我会离开的问题,以防有人开放的人有一个更好的解决方案。

ROUTEINFO CLASS:

 公共类RouteInfo
    {
        公共RouteInfo(数据的RouteData)
        {
            的RouteData =数据;
        }        公共RouteInfo(URI URI,串applicationPath)
        {
            的RouteData = RouteTable.Routes.GetRouteData(新InternalHttpContext(URI,applicationPath));
        }        公众的RouteData的RouteData {搞定;私人集; }        私有类InternalHttpContext:HttpContextBase
        {
            私人只读型Htt prequestBase _REQUEST;            公共InternalHttpContext(URI URI,字符串applicationPath):基地()
            {
                _request =新InternalRequestContext(URI,applicationPath);
            }            公共覆盖的Htt prequestBase请求{{返回_request; }}
        }        私有类InternalRequestContext:Htt的prequestBase
        {
            私人只读字符串_ap prelativePath;
            私人只读字符串_pathInfo;            公共InternalRequestContext(URI URI,字符串applicationPath):基地()
            {
                _pathInfo =; //uri.Query; (这是造成问题,看评论 - 斯图尔特)                如果(String.IsNullOrEmpty(applicationPath)||!uri.AbsolutePath.StartsWith(applicationPath,StringComparison.OrdinalIgnoreCase))
                    _ap prelativePath = uri.AbsolutePath;
                其他
                    _ap prelativePath = uri.AbsolutePath.Substring(applicationPath.Length);
            }            公共重写字符串鸭$ P $ {plativeCurrentExecutionFilePath获得{返回String.Concat(〜,_ap prelativePath); }}
            公众覆盖字符串PATHINFO {{返回_pathInfo; }}
        }
    }

URI扩展方法:

  ///<总结>
    ///为Uri类扩展方法
    ///< /总结>
    公共静态类UriExtensions
    {
        ///<总结>
        ///表示提供的URL是否基于在Global.asax中定义的MVC路由表中指定的控制器和动作值相匹配。
        ///< /总结>
        ///< PARAM NAME =URI获得包含的URL来评价474上的Uri对象; /参数>
        ///< PARAM NAME =controllerName>该控制器类的匹配LT的名称和/参数>
        ///< PARAM NAME =actionName>在操作方法的名称匹配< /参数>
        ///<退货和GT;真如果提供的URL映射到所提供的控制器类和动作方法,否则为false< /回报>
        公共静态布尔IsRouteMatch(此URI URI,串controllerName,串actionName)
        {
            RouteInfo routeInfo =新RouteInfo(URI,HttpContext.Current.Request.ApplicationPath);
            回报(routeInfo.RouteData.Values​​ [控制器]的ToString()== controllerName和放大器;&安培; routeInfo.RouteData.Values​​ [行动]的ToString()== actionName);
        }
    }

用法:

 乌里URL =新的URI(http://www.website.com/find-your-new-rental/northerncalifornia/sacramento.html);如果(url.IsRouteMatch(FindYourNewRental,社区))
{
    // 做一点事
}

 如果(Request.Url.IsRouteMatch(FindYourNewRental,社区))
    {
        // 做一点事
    }

好处:由于RouteInfo类给我回的RouteData的一个实例,我可以访问路径参数也是如此。这导致了另一种创造开放的扩展方法:

 公共静态字符串GetRouteParameterValue(此URI URI,串paramaterName)
        {
            RouteInfo routeInfo =新RouteInfo(URI,HttpContext.Current.Request.ApplicationPath);
            返回routeInfo.RouteData.Values​​ [paramaterName]!= NULL? routeInfo.RouteData.Values​​ [paramaterName]的ToString():空;
        }

现在哪些可以用于像这样:

 字符串someValue中= url.GetRouteParameterValue(参数名称);

How can I tell if a string matches a particular named route?

I have a route like this:

routes.MapRoute(
    "FindYourNewRental",
    "find-your-new-rental/{market}/{community}.html",
    new { controller = "FindYourNewRental", action = "Community" }
    );

string url = "http://www.website.com/find-your-new-rental/northerncalifornia/sacramento.html"

How can I programmatically tell if the 'url' string matches that route? Something like this:

// matches url with the named route "FindYourNewRental"
if (IsRouteMatch(url, "FindYourNewRental")) 
{
    // do something
}

public bool IsRouteMatch(string url, string routeName)
{
     // How do I code this function
}

解决方案

I solved this by adding a custom RouteInfo class which creates a new HttpContext with the supplied url and application path and uses that to obtain an instance of RouteData based on the new HttpContext object. I can then evaluate the Controller and Action values to see which route was matched. I have this wired up to an extension method on the Uri class. It feels a bit hackish and I was hoping there was a cleaner way to do this so I'll leave the question open in case someone else has a better solution.

ROUTEINFO CLASS:

public class RouteInfo
    {
        public RouteInfo(RouteData data)
        {
            RouteData = data;
        }

        public RouteInfo(Uri uri, string applicationPath)
        {
            RouteData = RouteTable.Routes.GetRouteData(new InternalHttpContext(uri, applicationPath));
        }

        public RouteData RouteData { get; private set; }

        private class InternalHttpContext : HttpContextBase
        {
            private readonly HttpRequestBase _request;

            public InternalHttpContext(Uri uri, string applicationPath) : base()
            {
                _request = new InternalRequestContext(uri, applicationPath);
            }

            public override HttpRequestBase Request { get { return _request; } }
        }

        private class InternalRequestContext : HttpRequestBase
        {
            private readonly string _appRelativePath;
            private readonly string _pathInfo;

            public InternalRequestContext(Uri uri, string applicationPath) : base()
            {
                _pathInfo = ""; //uri.Query; (this was causing problems, see comments - Stuart)

                if (String.IsNullOrEmpty(applicationPath) || !uri.AbsolutePath.StartsWith(applicationPath, StringComparison.OrdinalIgnoreCase))
                    _appRelativePath = uri.AbsolutePath;
                else
                    _appRelativePath = uri.AbsolutePath.Substring(applicationPath.Length);
            }

            public override string AppRelativeCurrentExecutionFilePath { get { return String.Concat("~", _appRelativePath); } }
            public override string PathInfo { get { return _pathInfo; } }
        }
    }

URI EXTENSION METHOD:

    /// <summary>
    /// Extension methods for the Uri class
    /// </summary>
    public static class UriExtensions
    {
        /// <summary>
        /// Indicates whether the supplied url matches the specified controller and action values based on the MVC routing table defined in global.asax.
        /// </summary>
        /// <param name="uri">A Uri object containing the url to evaluate</param>
        /// <param name="controllerName">The name of the controller class to match</param>
        /// <param name="actionName">The name of the action method to match</param>
        /// <returns>True if the supplied url is mapped to the supplied controller class and action method, false otherwise.</returns>
        public static bool IsRouteMatch(this Uri uri, string controllerName, string actionName)
        {
            RouteInfo routeInfo = new RouteInfo(uri, HttpContext.Current.Request.ApplicationPath);
            return (routeInfo.RouteData.Values["controller"].ToString() == controllerName && routeInfo.RouteData.Values["action"].ToString() == actionName);
        }
    }

USAGE:

Uri url = new Uri("http://www.website.com/find-your-new-rental/northerncalifornia/sacramento.html");

if (url.IsRouteMatch("FindYourNewRental", "Community"))
{
    // do something
}

OR

if (Request.Url.IsRouteMatch("FindYourNewRental", "Community"))
    {
        // do something
    }

ADDED BONUS: Because the RouteInfo class gives me back an instance of RouteData, I can access the route parameters as well. This led to the creation of another Uri extension method:

public static string GetRouteParameterValue(this Uri uri, string paramaterName)
        {
            RouteInfo routeInfo = new RouteInfo(uri, HttpContext.Current.Request.ApplicationPath);
            return routeInfo.RouteData.Values[paramaterName] != null ? routeInfo.RouteData.Values[paramaterName].ToString() : null;
        }

Which can now be used like so:

string someValue = url.GetRouteParameterValue("ParameterName");

这篇关于如何确定是否任意URL定义路由匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆