【问题标题】:How to determine if an arbitrary URL matches a defined route如何确定任意 URL 是否与定义的路由匹配
【发布时间】:2011-06-12 12:15:52
【问题描述】:

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

我有这样的路线:

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
}

【问题讨论】:

  • 你打算在哪里使用这个方法?在控制器、过滤器或...?
  • 在控制器中。我需要确定路线是否与三个特定路线之一匹配,并且我需要针对这三个特定路线中的每一个采取单独的操作。
  • 我不太明白你为什么要这样做?为什么不使用三个单独的操作?
  • 你误解了我对行动这个词的使用。我不会启动不同的 MVC 操作方法。我只需要根据引用 URL 在同一个操作方法中执行不同的逻辑。
  • 您可以使用 this.Request.Url 访问控制器中的 url,然后对其进行分析。这是你需要的吗?

标签: c# asp.net-mvc url routing asp.net-mvc-routing


【解决方案1】:

我通过添加一个自定义 RouteInfo 类解决了这个问题,该类使用提供的 url 和应用程序路径创建一个新的 HttpContext,并使用它来获取基于新 HttpContext 对象的 RouteData 实例。然后我可以评估 Controller 和 Action 值以查看匹配的路由。我将它连接到 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");

【讨论】:

  • mvccontrib 有一个测试助手库,用于对路由进行单元测试。有一个用于创建 RouteData 对象的字符串的扩展方法。因为它是 codeplex 上的一个开源项目,我建议你查看源代码以获取一些想法。
  • 这基本上是我所做的(除了在 Uri 对象上),但我创建了一个 HttpContext 实例,而不必像 MvcContrib 测试助手那样使用 Rhino Mocks。
  • 我在查询字符串参数被双重编码时遇到了一些问题。我发现这是由于 _pathInfo 被设置为查询字符串。这会导致 url 的最后一部分(在我的例子中是 action 值)错​​误地包含查询字符串,因此被双重编码。我已经更正了上面的代码来解决这个问题。
  • 我意识到这是一篇旧帖子,但我也有类似的需求。这仍然是您发现的模仿 URL 路由功能的最佳方法吗?
  • 到目前为止,但自从我发布此内容以来,我没有必要重新访问它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-08
  • 2021-03-09
  • 2017-09-18
  • 2011-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多