ASP.NET MVC URL路由问题
我是 MVC 和 URL 路由的新手,正在寻找一些指导。
我希望每个用户都有一个 URL,格式如下: http://www.example.com/username
所以我添加了以下路线:
routes.MapRoute(
"UserRoute", // Route name
"{username}", // URL
new { controller = "Users", action = "ViewUser", username = UrlParameter.Optional }
);
如果它有效,那么效果很好是第一个路由,但它弄乱了默认的 {controller}/{action}/{id}
路由。现在,当我尝试访问根页面时,它会尝试使用空参数(或使用“favicon.ico”作为参数)加载我的 UsersController“ViewUser”操作。
如果我将新路由放在默认路由之后,则 MVC 会尝试查找名为 username
的控制器,但会失败,因为找不到它。
有没有什么方法可以在不破坏常规路由系统的情况下获得 {username}
形式的 URL?我可能可以为我拥有的每个控制器编写一个自定义路由,但这似乎很容易出错。
I'm new to MVC and URL routing, and am looking for some guidance.
I would like to be able to have a URL per user, with the format:
http://www.example.com/username
So I added the following route:
routes.MapRoute(
"UserRoute", // Route name
"{username}", // URL
new { controller = "Users", action = "ViewUser", username = UrlParameter.Optional }
);
Which works great if it is the FIRST route, but it has messed up the default {controller}/{action}/{id}
route. Now when I try to visit the root page, it tries to load my UsersController "ViewUser" action with a null parameter (or with "favicon.ico" as the parameter).
If I put my new route AFTER the default route, then MVC tries to find the controller called username
and fails because it can't find it.
Is there any way to have URLs of the form {username}
without mucking up the regular routing system? I could probably write a custom route for every controller I have, but that seems error-prone.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以查看 此链接并查看是否有帮助。它还创建仅包含用户名的网址。
You can check out this link and see if it helps. It is also creating urls with just a username on them.
您可以对默认路由允许的控制器值施加约束,而不是为每个控制器创建路由。
当控制器与其中任何一个都不匹配时,它将尝试下一条路线
You can put a constraint to the allowed controller values for the default route, instead of creating a route for each controller.
when the controller does not match any of those it will try the next route