ASP.net MVC 路由参数异常

2023-12-28

我有一个需要 userId 参数的操作:

〜/用户/显示?userId=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?


不要按照下面建议的那样使用字符串。使用:

public ActionResult (int userId = 0)
{

}

这是最好的做法。

您还可以这样做:

public ActionResult (int? userId)
{
    if (userId.HasValue)
    {
        //...
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.net MVC 路由参数异常 的相关文章

随机推荐