ASP.net MVC route parameter exception

2019-06-25 12:23发布

问题:

I have and action which takes a userId parameter:

~/Users/Show?userId=1234

Everything works fine except when the userId provided is not an int or is missing.

Then it throws this exception:

            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.

How do I configure the route so the action isn't hit at all and it throws a 404 instead?

回答1:

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.

Keeping action paramters as strong types is a pattern to aim for.



回答2:

Don't use a string as suggested somewhere below. Use:

public ActionResult (int userId = 0)
{

}

That's the best practise.

You can also do:

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