C# MVC 路由 - 多条路由
我有一个默认的 c# mvc 路由:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}"
new { controller = "Home", action = "Index", id = "Welcome" }
);
现在我会得到如下网址:
mysite.com/Home/Index/Page1
mysite.com/Home/Index/Page2
mysite.com/Home/Index/Page3
mysite.com/Account/Login
mysite.com/Account/Etc
但我希望第一组具有较短的网址,例如:
mysite.com/Page1
mysite.com/Page2
mysite.com/Page3
mysite.com/Account/Login
mysite.com/Account/Etc
我希望代码非常简单,例如:
routes.MapRoute(
"Shorturl",
"{id}",
new { controller = "Home", action = "Index", id = "Welcome" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}"
new { controller = "Home", action = "Index", id = "Welcome" }
);
但这不起作用。它只会走第一条路线,而忘记第二条路线。 当只有一个参数时(比如 mysite.com/Page1) 并在有多个路由时选择第二条路由(例如 mysite.com/Account/Login)?
编辑: 我可以这样做:
routes.MapRoute("Short", "short/{id}", new { controller = "Home", action = "Indx", id = "Page1" } );
但是这样我的网址中就会有一个丑陋的“short/”。 我可以用以下方法修复它:
routes.MapRoute("Page1", "Page1", new { controller = "Home", action = "Index", id = "Page1" } );
但是我需要手动添加每个新页面......
I have a default c# mvc routes:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}"
new { controller = "Home", action = "Index", id = "Welcome" }
);
Now I will get urls like:
mysite.com/Home/Index/Page1
mysite.com/Home/Index/Page2
mysite.com/Home/Index/Page3
mysite.com/Account/Login
mysite.com/Account/Etc
But I would like to have the first set with a shorter url like:
mysite.com/Page1
mysite.com/Page2
mysite.com/Page3
mysite.com/Account/Login
mysite.com/Account/Etc
I expected the code to be really simple like:
routes.MapRoute(
"Shorturl",
"{id}",
new { controller = "Home", action = "Index", id = "Welcome" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}"
new { controller = "Home", action = "Index", id = "Welcome" }
);
But that doesn't work. It will only take the first route and forget the second.
How can you make your program take the first route when there is only one parameter (like
mysite.com/Page1) and take the second route when you have multiple routes (like mysite.com/Account/Login) ?
Edit:
I can do:
routes.MapRoute("Short", "short/{id}", new { controller = "Home", action = "Indx", id = "Page1" } );
But then I would have an ugly "short/" in the url.
I can fix it with:
routes.MapRoute("Page1", "Page1", new { controller = "Home", action = "Index", id = "Page1" } );
But then I need to add each new page manually...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可能想尝试这样的事情。
确保将其添加到默认路由之前(或者如果需要,甚至可以删除默认路由),
但添加这些的顺序很重要。
缺少一点信息,即控制器内的操作。
希望这有帮助。
问候。
You might want to try something like this.
make sure that you add this to the route before the default(or even remove the default if you want)
But the order in which these are added is important.
There was one bit of info missing, and that the Action within the controller.
Hope this helps.
Regards.