Asp.net mvc 3 - 按名称获取参数
有一个 url
http://mysite.com/en-us/articles/browse/en-us/12/byCategory
已知这些参数之一名为 culture
。当然,我可以调用 ViewContext.RouteData.Values["culture"]
来获取 culture
的 value,但它没有说我将其中的 en-us
参数(第一个或第二个)命名为 culture
。
我的任务是识别哪些参数名为 culture
,将其替换为指定值并返回新的 url。怎么做呢?
There is an url
http://mysite.com/en-us/articles/browse/en-us/12/byCategory
It's known that one of these parameters named culture
. Of course I can call ViewContext.RouteData.Values["culture"]
to get the value of the culture
, but it doesn't say me which en-us
parameter (first or second) named culture
.
My task is recognize which of parameters named culture
, replace it with specified value and return the new url. How to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能有两个同名的段参数
因此,如果您说
ViewContext.RouteData.Values["culture"]
,您将获得与特定相关的正确区域性值/em> 分段第一个或第二个,具体取决于您的路由 URL 定义,其可能如下所示:如您所见,只有一个名为
culture
的分段参数。获取当前路由的 URL 定义
但是,否则您可以通过以下方式获取当前正在执行的路由 URL 定义来定位正确的段:
将
RouteBase
转换为Route
可能在 99% 的情况下有效,因为使用自定义路由类并不常见,但尽管自定义类更有可能从Route
继承,而不是从RouteBase
继承。解析此 URL 定义可能是一项更具挑战性的任务,具体取决于路由定义的复杂性。但您或多或少可以成功地将任何 URL 定义与请求 URL 段进行匹配。这可能正是您所追求的。
让当前路由为您进行替换
但是,您可以让路由本身为您完成此操作,而不是解析路由的 URL 并替换正确的段:
You can't have two segment parameters with the same name
So if you say
ViewContext.RouteData.Values["culture"]
you will get the correct culture value that is related to a specific segment either the first or the second one, depending on your route URL definition which may look like:As you can see there's only one segment parameter called
culture
.Get current route's URL definition
But otherwise you could get the currently executing route URL definition to locate the correct segment by:
Casting
RouteBase
toRoute
would probably work in 99% of cases because using custom route classes isn't that common, but even though custom classes are more likely to inherit fromRoute
thanRouteBase
.Parsing this URL definition may be a more challenging task depending on the complexity of your route definitions. But you could more or less successfully match any URL definition against request URL segments. And this may be exactly what you're after.
Let current route do the replacement for you
But instead of parsing route's URL and replacing correct segment, you could let route itself do it for you simply by: