如何删除“详细信息” 在 MVC URL 路由中,但保持其他操作不变?

发布于 2024-07-24 21:55:02 字数 901 浏览 3 评论 0原文

我想为具有正常 CRUD 操作的控制器设置一条路由,但希望“详细信息”操作不在 URL 中显示“详细信息”。 Stackoverflow 似乎配置了这种类型的路由:

http://stackoverflow.com/questions/999999/
http://stackoverflow.com/questions/ask

使用这个类比,我的路由当前看起来像:

http://stackoverflow.com/questions/Details/999999/

通过添加以下路由,我能够删除 Details

routes.MapRoute("Q1", "questions/{id}", 
    new { controller = "Questions", action = "Details" });

但是,在控制器上拉起其他操作(例如本例中的 /questions/new)抱怨无法解析 id。

有没有办法设置路由,以便我不必手动将所有其他操作(MapRoute“items/create”、“items/delete”等)手动输入到 Global.asax.cs 中? 我本质上希望有第二条路线,例如:

routes.MapRoute("Q2", "questions/{action}", 
    new { controller = "Questions", action = "Index" });

...并且如果 {id} 匹配整数,则让路由引擎使用路线 Q1,如果 {action} 匹配整数,则让路由引擎使用路线 Q1是一个字符串。 这可能吗?

I would like to set up a route for a controller that has the normal CRUD operations, but would like the Details action not show 'Details' in the URL. Stackoverflow seems to have this type of routing configured:

http://stackoverflow.com/questions/999999/
http://stackoverflow.com/questions/ask

Using this analogy, my routes currently look like:

http://stackoverflow.com/questions/Details/999999/

By adding the following route I was able to get Details removed:

routes.MapRoute("Q1", "questions/{id}", 
    new { controller = "Questions", action = "Details" });

However, pulling up other actions on the controller (e.g. /questions/new for this example) is complaining that the id cannot be parsed.

Is there a way to set up the routes so that I don't have to manually enter all the other actions (MapRoute "items/create", "items/delete", etc.) manually into the Global.asax.cs? I essentially would like to have a second route like:

routes.MapRoute("Q2", "questions/{action}", 
    new { controller = "Questions", action = "Index" });

... and have the routing engine use route Q1 if {id} matches an integer, and {action} if it is a string. Is this possible?

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

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

发布评论

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

评论(1

如梦 2024-07-31 21:55:02

如果您在第一个上设置路由约束,以便 id 字段只能是整数,那么我相信任何其他操作都会落入默认值。

routes.MapRoute("Q1", 
   "questions/{id}", 
   new {controller = "Questions", action = "Details"},
   new { id=@"\d+" });

其他任何事情都应该由默认路由处理。 所以“questions/3553”会命中这个,但“questions/ask”不会匹配。 您可能希望将更具体的路线放在 Global.asax.cs 文件中。

If you put a route constraint on the first one so that the id field can only be an integer then I believe any other actions will fall through to the default.

routes.MapRoute("Q1", 
   "questions/{id}", 
   new {controller = "Questions", action = "Details"},
   new { id=@"\d+" });

Anything else should be handled by the default route. So "questions/3553" would hit this one but "questions/ask" would not match. You'll probably want to put the more specific route first in your Global.asax.cs file.

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