ASP.NET MVC URL路由问题

发布于 2024-10-21 10:37:04 字数 706 浏览 7 评论 0原文

我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

何其悲哀 2024-10-28 10:37:04

您可以查看 此链接并查看是否有帮助。它还创建仅包含用户名的网址。

You can check out this link and see if it helps. It is also creating urls with just a username on them.

您可以对默认路由允许的控制器值施加约束,而不是为每个控制器创建路由。

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL
    new { controller = "controller1", action = "defaultaction", id = UrlParameter.Optional }, //default values
    new { controller = @"controller1|controller2|controller3|..." }
);

当控制器与其中任何一个都不匹配时,它将尝试下一条路线

You can put a constraint to the allowed controller values for the default route, instead of creating a route for each controller.

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL
    new { controller = "controller1", action = "defaultaction", id = UrlParameter.Optional }, //default values
    new { controller = @"controller1|controller2|controller3|..." }
);

when the controller does not match any of those it will try the next route

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文