我们可以在 Asp.net MVC 应用程序的 URL 中仅使用控制器名称和 id 参数吗

发布于 2024-12-25 22:23:41 字数 341 浏览 5 评论 0原文

假设我有一个名为 category 的控制器,其操作方法 Index 接受 id 作为参数。

因此,URL 如下所示:category/Index/foo。正如您所看到的,索引部分似乎不太正确。像这样的 URL:category/foo 将更容易阅读和理解。

就像在SO中一样,这些人使用:question/857344

我怎样才能实现这样的URL。在我的路由中,我为所有三个设置了默认值:控制器、操作和 ID。但是,当我尝试访问 category/foo 时,我收到“404 - 资源未找到”

Suppose, I have a controller named category with an action method, Index which takes id as parameter.

Therefore, the URL appears like this : category/Index/foo. As you can see, the Index segment just doesn't seem right. A URL such as this : category/foo will be more readable and understandable.

Just like in SO, these guys use : question/857344

How can I achieve such a URL. In my routes, I have set defaults for all three : controller, action and id. But, when i try to visit category/foo, I get the "404 - resource not find"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

心欲静而疯不止 2025-01-01 22:23:41
routes.MapRoute(
               "Category/{id}",
               new { controller = "Category", action = "Index", id = UrlParameter.Optional } // Parameter defaults
               );

您可以将其映射为您想要的外观,然后指定操作。

还要确保将其放在默认路由之前

routes.MapRoute(
               "Category/{id}",
               new { controller = "Category", action = "Index", id = UrlParameter.Optional } // Parameter defaults
               );

You map it how you want it to look then specify the Action.

Also make sure you put it before the default route

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