我有一个需要 userId 参数的操作:
~/Users/Show?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)
{
//...
}
}
关于asp.net-mvc - ASP.net MVC 路由参数异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9532702/