Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC throws error when id is null

I have a publicly available controller (The action cannot be hidden under any security attribute) . The controller has an action which is available publicly as well.

Following is a sample structure of the controller :

 public SomeController : Controller {


       [HttpGet] 
       public ActionResult show(int id){

       }

 }

The action has a id field which is required. However throws an error which unnecessary adds to the logs when someone enters a malformed URL without the required id (or when search engine bots hit the a URL with the required id).

What should be the ideal solution to deal with this solution.

Possible solutions that come to my mind are :

  • Set the id as Nullable (int? id) and explicitly handle the case of not having a value by redirecting the caller to some other page showing appropriate errors
  • explicitly send a 404 error

Is there a generic way using Attributes to do this?

P.S : (to be specific) by explicit I mean writing if else conditions to handle such cases per controller.

I would appreciate any hints in the right direction.

like image 356
frictionlesspulley Avatar asked Dec 31 '25 18:12

frictionlesspulley


1 Answers

You need a route constraint. This will help the router throw out URLs earlier (resulting in a 404) rather than later (the route is valid, goes to action, action barfs because a parameter is missing).

http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-a-route-constraint-cs

Example default route (potentially replacing the existing one in your global.asax.cx):

// order is important; more specific routes to less specific routes is what you want
//
// default index action, with no ID
routes.MapRoute(
    "Default_Index",
    "{controller}/",
    new {controller="Home", action="Index"}
 );

// default create action, with no ID
routes.MapRoute(
    "Default_Create",
    "{controller}/Create",
    new {controller="Home", action="Create"}
 );

// default action requiring an ID (such as EDIT)
routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new {controller="Home", action="Index"},
    new {id = @"\d+" }
 );
like image 112
moribvndvs Avatar answered Jan 05 '26 04:01

moribvndvs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!