具有不同参数名称的 Asp.Net 路由
我正在尝试映射某些路线,以便自动生成的网址看起来像 对于这两个代码块,Admin/controller/action/param
@Url.Action("action","controller",new{id="param"})
和 @Url.Action("action","controller",new{type="param"})
我在区域注册中做了以下操作,
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index",
id = UrlParameter.Optional },
new string[] { "namespaces" });
context.MapRoute(
"Admin_type",
"Admin/{controller}/{action}/{type}",
new { action = "Index",
type = UrlParameter.Optional },
new string[] { "namespaces" });
当参数名称为 id,生成的url符合预期,但是当参数名称为
type
时,而不是controller/action/typevalue
,它会生成类似controller/action/? type=typevalue
有没有办法生成url 类似 controller/action/typevalue
保持 Admin_default
路由的生成器行为完好无损?
I'm trying to map certain routes so that auto generated Urls will look likeAdmin/controller/action/param
for both of these code blocks,@Url.Action("action","controller",new{id="param"})
and@Url.Action("action","controller",new{type="param"})
What I did was the following in the area registration,
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index",
id = UrlParameter.Optional },
new string[] { "namespaces" });
context.MapRoute(
"Admin_type",
"Admin/{controller}/{action}/{type}",
new { action = "Index",
type = UrlParameter.Optional },
new string[] { "namespaces" });
when parameter name is id
, url generated is as expected, but when parameter name is type
, instead of controller/action/typevalue
, it generates something like controller/action/?type=typevalue
Is there a way to generate the url something like controller/action/typevalue
keeping the generator behaviour for Admin_default
route intact?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
发生这种情况是因为第一个路由用于映射url(id 是可选的)。
您可以尝试为您的路线添加一些限制。我猜你的 id 参数是一个整数,类型参数是一个字符串。在这种情况下,您可以尝试使用以下路线:
您可以找到有关路线约束的更多信息 这里。
That happens because first route is used to map the url (id is optional).
You could try adding some constraints to your routes. I'm guessing your id parameter is an integer and type parameter is a string. In that case you can try with this routes:
You can find more info on route constraints here.
您是否尝试过删除 id 上的可选默认值?在这种情况下,当仅提供类型参数时,第一条路由不应匹配。
编辑:再次阅读你的问题后,我的解决方案并没有保持你的第一条路线完好无损......
Have you tried removing the Optional default value on id ? In this case, the first route shouldn't match when providing only the type parameter.
EDIT: After reading again your question, my solution doesn't keep your first route intact ...
您只需要一条路线。
在你的控制器中你的
URL:
http://website/Admin/index/hello
http://website/Admin/type/342
You only need the one route.
in your controller you
URLs:
http://website/Admin/index/hello
http://website/Admin/type/342