ASP.NET MVC:可用路由数据的 Uri
我的问题很简单。我有一个 Uri,我想弄清楚它映射到哪个路由,以便我可以对路由的各个部分进行一些检查:控制器、操作等。
如何从 Uri 转到 RouteData 或 Route?
My problem is pretty simple. I've got a Uri and I want to figure out which route it maps to so I can do some checks on the various pieces of the route: controller, action, etc.
How do I go from Uri to RouteData or Route?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据@tvanfosson 的指导,我想出了一个可以满足我需要的课程。请注意,
GetRouteData
实际上查看的是RequestContextBase
类上的AppRelativeCurrentExecutionFilePath
和PathInfo
属性,而不是>Url
属性。Based on @tvanfosson's direction, I came up with a class that does what I need. Note that the
GetRouteData
actually looks at theAppRelativeCurrentExecutionFilePath
and thePathInfo
properties on theRequestContextBase
class, not theUrl
property.您可以尝试扩展 HttpRequestBase 并覆盖 Uri 属性,以便可以将 Uri 分配给请求上的属性。然后重写 HttpContextBase 以允许您在上下文上设置 Request 属性。然后,您可以使用 RouteCollection 类上的 GetRouteData() 方法来获取合适的 RouteValueDictionary。请注意,RouteCollection 可用作 RouteTable 类的静态属性。
更新:
对于您的用例(评论),您可能可以简单地匹配控制器/操作:
You might try extending HttpRequestBase and override the Uri property so that you can assign your Uri to the property on the request. Then override HttpContextBase to allow you to set the Request property on the context. You can then use the GetRouteData() method on the RouteCollection class to get a suitable RouteValueDictionary. Note that the RouteCollection is available as a static property on the RouteTable class.
Update:
For your use case (comments), you might be able to simply match on the controller/action:
根据您是否同意更改当前请求的路径(就我而言),这是一个非常简单的解决方案,不涉及模拟任何内容:
Depending on if you are okay with changing the path of the current request (In my case I am) here is a very easy solution that doesn't involve mocking up anything: