ASP.net MVC route parameter exception

I have an action that takes the userId parameter:

~ / Users / show? User ID = 1234

Everything works just fine unless the provided userId is int or 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 to set up a route so that the action fails at all, and instead it throws 404?

+4
source share
2 answers

As mentioned in my commentary on Ufuk Hacıoğulları, you must handle validation either by adding a constraint to the route, or by using the NULL type if the parameter can be empty.

For the previous approach, if you have a corresponding restriction, this means that your route will not be raised - you will need to catch the entire route or other error handling. For a type with a null value, you can check in action whether it has a value and acts accordingly.

Saving action parameters as strong types is a template to strive for.

+1
source

Do not use the string as shown below. Using:

 public ActionResult (int userId = 0) { } 

This is the best practice.

You can also do:

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

Source: https://habr.com/ru/post/1399376/


All Articles