简体   繁体   English

在MVC 4中将base / id路由到controller / action / id

[英]Route base/id to controller/action/id in mvc 4

I want to redirect users when they enter a URL into the browser based on the ID. 我想在用户根据ID向浏览器输入URL时重定向他们。 For example, a user enters: 例如,用户输入:

http://localhost:50431/10213

and they will be redirected to: 并将其重定向到:

http://localhost:50431/home/job/10213

Default Route: 默认路线:

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{jobno}",
                defaults: new { controller = "Home", action = "Job", jobno = UrlParameter.Optional }
            );

How can I achieve this? 我该如何实现?

You could try something like this: 您可以尝试这样的事情:

routes.MapRoute(
  name: "Job Number",
  url: "{jobno}",
  defaults: new { controller = "Home", action = "Job" },
  new { jobno = @"[0-9]*" }      
);

And put it above the other route. 并将其放在另一条路线之上。 The added parameter is to avoid the route catching urls like http://localhost:50431/foobar , but only the ones that contain numbers. 添加的参数是为了避免路由捕获诸如http://localhost:50431/foobar类的url,但只能http://localhost:50431/foobar那些包含数字的URL。

Please note I don't have a way of testing this at the moment so you may have to tweak it slightly. 请注意,我目前没有测试方法,因此您可能需要稍作调整。

I think this is the best solution: 我认为这是最好的解决方案:

routes.MapRoute(
  name: "Job Number",
  url: "{jobno}",
  defaults: new { controller = "Home", action = "Job", .jobno = UrlParameter.Optional },
  constraints: new { jobno = @"[0-9]*" }      
);

I have tested this and it works properly, his reply in the comment did not work properly for me. 我已经对此进行了测试,并且可以正常工作,他在评论中的回复对我来说并不正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM