ASP.net MVC路线的参数异常 [英] ASP.net MVC route parameter exception
问题描述
我和行动,这需要userid参数:
I have and action which takes a userId parameter:
〜/用户/显示?用户id = 1234
~/Users/Show?userId=1234
一切工作只是罚款时提供的用户id不是int或丢失。
Everything works fine except when the userId provided is not an int or is missing.
然后抛出这个异常:
Message: The parameters dictionary contains a null entry for parameter 'userId' of
non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Show(Int32,
System.Nullable`1[System.Boolean], System.String)' in 'S4U.Web.Mvc.Controllers.ProfileController'. An optional parameter must be a reference type,
a nullable type, or be declared as an optional parameter.
Parameter name: parameters
..之后,用户会被重定向到错误页面。
..after which the user is redirected to the error page.
我如何配置路由,这样的动作根本没有被击中,它抛出一个404呢?
How do I configure the route so the action isn't hit at all and it throws a 404 instead?
推荐答案
正如我在上UfukHacıoğulları的回答您应该通过增加一个约束路由处理验证评论中提及,通过具有可空类型,如果该参数可以是空的
As mentioned in my comment on Ufuk Hacıoğulları's answer you should handle validation either through adding a constraint to a route, through having a nullable type if the parameter can be empty.
有关,如果你有一个适当的约束,这意味着你的路线不会被拾起前一种方法 - 你需要一个包罗万象的路线或其他错误处理。对于可空类型你可以在它是否有一个值的动作测试并采取相应的行动。
For the former approach if you have an appropriate constraint this means your route will not be picked up - you will need a catch all route or other error handling. For the nullable type you can test in the action whether it has a value and act accordingly.
保持动作paramters强类型是瞄准一个模式。
Keeping action paramters as strong types is a pattern to aim for.
这篇关于ASP.net MVC路线的参数异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!