如何通过URL获取RouteData?

时间:2010-08-23 07:18:09

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

我需要在ASP.NET MVC应用程序中通过给定的URL字符串获取RoutData

我找到了基于我的网址字符串模拟HttpContextBase的方法,然后将其传递给Route Parsing (Uri to Route)帖子中的RouteTable.Routes.GetRouteData()方法。

如何使用HttpContextBase模拟RouteData通过网址字符串检索RouteTable.Routes.GetRouteData() 还是有另一种方法可以通过网址检索RouteData吗?

2 个答案:

答案 0 :(得分:39)

我使用Moq来确定HttpContextBaseGetRouteData()的成员使用情况。他们是:

  • 请求
    • AppRelativeCurrentExecutionFilePath
    • PATHINFO

Request.AppRelativeCurrentExecutionFilePath应返回~的路径,这是我真正需要的路径,因此实用程序类可能就像这样:

public static class RouteUtils
{
    public static RouteData GetRouteDataByUrl(string url)
    {
        return RouteTable.Routes.GetRouteData(new RewritedHttpContextBase(url));
    }

    private class RewritedHttpContextBase : HttpContextBase
    {
        private readonly HttpRequestBase mockHttpRequestBase;

        public RewritedHttpContextBase(string appRelativeUrl)
        {
            this.mockHttpRequestBase = new MockHttpRequestBase(appRelativeUrl);
        }


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

        private class MockHttpRequestBase : HttpRequestBase
        {
            private readonly string appRelativeUrl;

            public MockHttpRequestBase(string appRelativeUrl)
            {
                this.appRelativeUrl = appRelativeUrl;
            }

            public override string AppRelativeCurrentExecutionFilePath
            {
                get { return appRelativeUrl; }
            }

            public override string PathInfo
            {
                get { return ""; }
            }
        }
    }
}

然后,您可以像这样使用它(例如在 ~/Error/NotFound 上):

var rd = RouteUtils.GetRouteDataByUrl("~/Error/NotFound")

哪个应该返回一个如下所示的对象:

RouteData.Values
{
    controller = "Error",
    action = "NotFound"
}

答案 1 :(得分:7)

这对我有用(.NET 4.5,MVC 5): https://average-joe.info/url-to-route-data/

System.Web.Routing.RouteData routeFromUrl =
    System.Web.Routing.RouteTable.Routes.GetRouteData(
            new HttpContextWrapper(
                new HttpContext(
                    new HttpRequest(null, path, query),
                    new HttpResponse(new System.IO.StringWriter()))));