问题描述
是否可以不执行任何操作来创建路线?
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
其中1234
是ID
,而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.
因此,如果您希望此设置正常运行,则需要指定一些 constraints
.另外,请不要忘记,路由定义的顺序很重要,因为它们会按照您定义的顺序进行解析.因此,请确保在顶部放置更具体的路线.
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.
这篇关于如何不采取行动就创建一条路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!