如何通过 URL 获取 RouteData? [英] How to get RouteData by URL?
问题描述
我需要通过 ASP.NET MVC 应用程序中的给定 URL 字符串获取 RoutData
.
I need to get RoutData
by given URL string in ASP.NET MVC application.
我找到了基于我的 URL 字符串模拟 HttpContextBase
然后将它传递给 RouteTable.Routes.GetRouteData()
方法在
I've found the way that I need to mock HttpContextBase
based on my URL string and then pass it to RouteTable.Routes.GetRouteData()
method in Route Parsing (Uri to Route) thread.
如何使用 RouteTable.Routes.GetRouteData()
模拟 HttpContextBase
以通过 URL 字符串检索 RouteData
?或者有其他方法可以通过 URL 检索 RouteData
吗?
How to mock HttpContextBase
to retrieve RouteData
by URL string using RouteTable.Routes.GetRouteData()
?
Or is there another way to retrieve RouteData
by URL?
推荐答案
我使用了 Moq 确定在 GetRouteData()
中使用了 HttpContextBase
的哪些成员.它们是:
I used Moq to determine what members of HttpContextBase
are used in GetRouteData()
. They are:
- 请求
- AppRelativeCurrentExecutionFilePath
- 路径信息
Request.AppRelativeCurrentExecutionFilePath
应该返回带有~
的路径,这是我真正需要的,所以实用程序类可能是这样的:Request.AppRelativeCurrentExecutionFilePath
should return path with~
, what I exactly need, so utility class may be like this one: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
上):Then, you can use it like this (for example on
~/Error/NotFound
):var rd = RouteUtils.GetRouteDataByUrl("~/Error/NotFound")
应该返回一个看起来像这样的对象:
Which should return an object that looks like this:
RouteData.Values { controller = "Error", action = "NotFound" }
这篇关于如何通过 URL 获取 RouteData?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!