如何确定任意 URL 是否与定义的路由匹配

发布于 2024-10-13 04:27:44 字数 624 浏览 4 评论 0原文

如何判断字符串是否与特定的命名路由匹配?

我有这样的路线:

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"

如何以编程方式判断“url”字符串是否与该路线匹配?像这样的东西:

// 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
}

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
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

余生一个溪 2024-10-20 04:27:44

我通过添加一个自定义 RouteInfo 类解决了这个问题,该类使用提供的 url 和应用程序路径创建一个新的 HttpContext,并使用它来获取基于新 HttpContext 对象的 RouteData 实例。然后我可以评估控制器和操作值以查看匹配的路由。我将其连接到 Uri 类上的扩展方法。这感觉有点黑客,我希望有一种更干净的方法来做到这一点,所以我将保留这个问题,以防其他人有更好的解决方案。

ROUTEINFO 类:

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 扩展方法:

    /// <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);
        }
    }

用法:

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

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

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

添加奖励: 因为RouteInfo 类返回 RouteData 的实例,我也可以访问路由参数。这导致了另一个 Uri 扩展方法的创建:

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;
        }

现在可以像这样使用它:

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

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");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文