如何不采取行动就创建一条路线? [英] How to create a route without action?

查看:86
本文介绍了如何不采取行动就创建一条路线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以不执行任何操作来创建路线?

Is it possible to create a route without action?

我有以下默认路由:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

但是我也想要这样的URL:http://mysite/bar/1234其中1234ID,而bar是控制器.

But I also I want to have URLs like this: http://mysite/bar/1234 where 1234 is the ID and bar is the controller.

所以我创建了以下路线:

So I created the following route:

routes.MapRoute(
    name: "BarRoute",
    url: "{controller}/{id}",
    defaults: new { controller = "bar", action = "Index", id = UrlParameter.Optional }
);

但是当我导航到http://mysite/bar/1234时,它说找不到资源.在第二条路线中我做错了什么?

But when I navigate to http://mysite/bar/1234, it said the resource is not found. What did I do wrong in the second route?

推荐答案

在没有任何约束的情况下,您不能按照以下顺序使用以下2条路线

You cannot have the following 2 routes in that order without any constraints

  • {controller}/{action}/{id}
  • {controller}/{id}
  • {controller}/{action}/{id}
  • {controller}/{id}

这2条路由不兼容.当您尝试访问http://mysite/bar/1234时,路由引擎正在分析您的路由,而/bar/1234匹配您的第一条路由.除了我猜您没有在Bar控制器上执行名为1234的操作外.

Those 2 routes are incompatible. When you attempt to access http://mysite/bar/1234, the routing engine is analyzing your routes and /bar/1234 matches your first route. Except that I guess you do not have an action called 1234 on the Bar controller.

因此,如果您希望此设置正常运行,则需要指定一些

So if you want this setup to work you need to specify some constraints. Also don't forget that the order of your routes definition is important because they are resolved in the order you defined them. So make sure you place more specific routes at the top.

这篇关于如何不采取行动就创建一条路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆