MVC 中的默认数字根路由
我有一个网站,我想要
/22 Redirect to
/user/22
等等,但是还有其他 mvc 视图和控制器,它们都工作正常,我使用了以下路线,但它不起作用。
routes.MapRoute(
"Final",
"{id}",
new { controller = "Root", action = "Index"},
new { id = @"\d+" },
new string[] { "MyWebApp.Controllers" }
);
理想情况下,此路由仅在 url 片段为数字时才有效。
我在 MyWebApp.Controllers 命名空间中也有一个 RootController 。它所做的只是重定向到其他页面,如下所示,
public class RootController : Controller
{
public ActionResult Index(long id) {
return RedirectPermanent("/user/" + id);
}
}
现在,我们必须这样做,因为它是旧网站的升级,我们无法更改 url 方案,因为它是公开的并且正在使用。
注意:URL /user/22 等工作正常,只有这个根 URL 出现问题。
I have a website and I want
/22 Redirect to
/user/22
etc and so on, however there are other mvc views and controllers and they all work alright, I have used following Route but its not working.
routes.MapRoute(
"Final",
"{id}",
new { controller = "Root", action = "Index"},
new { id = @"\d+" },
new string[] { "MyWebApp.Controllers" }
);
Ideally this route should only work if url fragment is numeric.
I have a RootController in MyWebApp.Controllers namespace as well. And all it does is redirect to other page as below,
public class RootController : Controller
{
public ActionResult Index(long id) {
return RedirectPermanent("/user/" + id);
}
}
Now, we have to do this because it is an upgrade to old website and we cannot change url scheme, because its public and in use.
Note: URLs /user/22 etc are working correctly, only this root URL is giving problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已经测试了这条路线:
它正常工作。但如果您遇到问题,我猜测您所需的 URL 与之前的另一个路由匹配。将此路线作为您的第一条路线,看看是否可以解决问题。
例如,如果您的路线如下所示:
您将收到404 未找到资源。但是,如果您像这样切换它们:
那么您将通过
/1234
之类的请求获得所需的路由。I have tested this route out:
It is working just as it should. But if you're having an issue with it, I'm guessing that your desired URL is matching another route prior to it. Put this route as your first route and see if that fixes it.
For instance, if your routes look like this:
You will get a 404 resource not found. But if you switch them like this:
Then you'll get the desired routing with a request like
/1234
.