如何通过URL获取RouteData?

我需要在ASP.NET MVC应用程序中通过给定的URLstring来获取RoutData

我发现我需要根据我的URLstring来模拟HttpContextBase ,然后将它传递给Route Parsing(Uri to Route)线程中的RouteTable.Routes.GetRouteData()方法。

如何模拟HttpContextBase通过使用RouteTable.Routes.GetRouteData() URLstring检索RouteData 或者有另一种方式来检索URL的RouteData

我使用Moq来确定GetRouteData()中使用了哪些HttpContextBase成员。 他们是:

  • 请求
    • AppRelativeCurrentExecutionFilePath
    • PATHINFO

Request.AppRelativeCurrentExecutionFilePath应该返回~ ,我确切需要的path,所以实用程序类可能是这样的:

 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 ,例如, RouteUtils.GetRouteByUrl("~/Error/NotFound")返回类似

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

也许这对任何人都有帮助。

这适用于我(.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()))));