ASP.net MVC路由参数异常

时间:2012-03-02 11:42:21

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-routing

我有一个带有userId参数的动作:

〜/用户/显示?用户id = 1234

除非提供的userId不是int或缺失,否则一切正常。

然后它抛出了这个异常:

            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

..之后用户被重定向到错误页面。

如何配置路线以便根本不会触发操作,而是抛出404?

2 个答案:

答案 0 :(得分:4)

不要在下面的某处使用字符串。使用:

public ActionResult (int userId = 0)
{

}

这是最好的做法。

你也可以这样做:

public ActionResult (int? userId)
{
    if (userId.HasValue)
    {
        //...
    }
}

答案 1 :(得分:1)

正如我在UfukHacıoğulları的回答评论中提到的那样,您应该通过向路径添加约束来处理验证,如果参数可以为空,则通过具有可为空类型。

对于前一种方法,如果你有一个适当的约束,这意味着你的路线不会被选中 - 你将需要捕获所有路线或其他错误处理。对于可空类型,您可以在操作中测试它是否具有值并相应地执行操作。

将行动参数保持为强类型是一种瞄准的模式。