frictionlesspulley
frictionlesspulley

Reputation: 12408

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 :

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.

Upvotes: 3

Views: 1103

Answers (2)

Rajeesh
Rajeesh

Reputation: 4495

I would suggest to return 404 status with a custom error page because some one is requesting a resource that doesn't exists.

You can make it as a Nullable type, if it can return a result which represents that request otherwise return 404 status.

For e.g. action method Index(int? id) could return list of items, if id is null or return that specific item. Depending on your business scenario.

Upvotes: 1

moribvndvs
moribvndvs

Reputation: 42497

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+" }
 );

Upvotes: 3

Related Questions