asp.net-mvc - ASP.net MVC 路由参数异常

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

我有一个需要 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/

相关文章:

javascript - 隐藏值不是由 jQuery 设置的?

c# - SignalR Context.User.Name 返回空

asp.net-mvc - 模型绑定(bind)下拉选择值

c# - .NET MVC 路由(忽略文件扩展名)

c# - AsPerRequestSingleton() 使用带有 TinyIOC 容器的工厂方法注册

asp.net-mvc - 在 Windows 8 中的 IIS 8 上使用 .NET 4.5 的 MVC 4 网站给出 403.14 禁止错误

jQuery AJAX 加载未在 ASP.NET MVC Controller 操作上执行

asp.net-web-api - 使用路由与查询字符串参数是错误的吗?

c# - 将查询字符串从对象转换为对象

asp.net-mvc - 如何在 jqueryui 工具提示中显示 jqueryui 验证错误消息