我需要通过ASP.NET MVC应用程序中给定的URL字符串获取RoutData。
我发现了我需要模拟HttpContextBase基于我的URL字符串,然后将其传递给RouteTable.Routes.GetRouteData()方法在Route Parsing (Uri to Route)线程的方式。
如何模拟HttpContextBase通过URL字符串使用RouteTable.Routes.GetRouteData()检索RouteData?
还是有另一种方法来通过URL检索RouteData?
解决方法
我使用
Moq来确定HttpContextBase的什么成员在GetRouteData()中使用。他们是:
>请求
> 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,例如,RouteUtils.GetRouteByUrl(“〜/ Error / NotFound”)返回类似
RouteData.Values { controller = "Error",action = "NotFound" }
也许这将有助于任何人。