问题描述
我有这条路线:
routes.MapRoute(
"PlaceDetails",
"{controller}/{action}/{id}",
new { controller = "Place", action = "Details", id = UrlParameter.Optional }
);
这可以解决以下问题:mysite.com/place/details/123
This routes this fine:mysite.com/place/details/123
使ID 123可用于位置控制器的details操作-然后可以查找位置'123'.
Making Id 123 available to the details action of the place controller - which can then lookup place '123'.
但是-此URL也传递给了控制器:mysite.com/place/details/
However - this URL is also passed to the controller:mysite.com/place/details/
我希望它返回HttpNotFound
-但它向控制器发送一个空ID-并要求我处理.
I want this to return HttpNotFound
- but it sends a null Id to the controller - and requires me to handle that.
如果路由本身实现了此目的,而不是在控制器本身中进行不正常的空检查,则似乎更加巧妙.
It seems neater if the route itself achieves this rather than needing unseemly null checks in the controller itself.
我在Google上没有发现有关此特定问题的任何信息.
I have found nothing in Google about this specific issue.
我该怎么做?
推荐答案
要使id
值为必需,则不能将其设置为UrlParameter.Optional
或提供任何其他默认值.该网址段中没有值,也没有默认值,该路由将与请求不匹配.
To make the id
value required, you must not set it as UrlParameter.Optional
or provide any other default value. With no value in the URL segment, and no default, the route won't match the request.
routes.MapRoute(
"PlaceDetails",
"{controller}/{action}/{id}",
new { controller = "Place", action = "Details" }
);
但是您可能还需要以另一种方式限制该路由,以防止在不该匹配的情况下匹配该路由.
But you probably also need to constrain the route in another way to prevent it from matching in cases where it shouldn't.
routes.MapRoute(
"PlaceDetails",
"Place/{action}/{id}",
new { controller = "Place", action = "Details" }
);
有关详细信息和其他选项,请参见为什么在asp.net mvc中先将特殊路由映射到普通路由之前?.
See Why map special routes first before common routes in asp.net mvc? for details and additional options.
这篇关于使ASP.NET MVC路由ID参数为必需的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!