4

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?

2 Answers 2

4

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)
    {
        //...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.