12

I'm getting the following error a lot when the Google bot comes by:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Show(Int32)' in 'someclass'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters

I was wondering if it would be possible to have the application throw 404's instead of missing parameter exception in this case.

Thanks!

Update to clarify what I want is that all cases for this particular error throw a 404 error instead of a 500. Preferably by writing a wrapper of some kind that only catches this error.

Rup
  • 33,765
  • 9
  • 83
  • 112
TomHastjarjanto
  • 5,386
  • 1
  • 29
  • 41

3 Answers3

8
public ActionResult Index(int? id)
{
   if(!id.HasValue())
   {
     throw new HttpException(404, "Are you sure you're in the right place?");
   }
}
moshjeier
  • 196
  • 6
  • 4
    This works, but you have to put this code into *every* action method. Isn't there a better way of doing this centrally? – Drew Noakes Oct 15 '13 at 11:07
  • @DrewNoakes yea that's what I'm thinking too. The other option is to do int id = 0 and default it to 0 if nothing is passed in but you still need to do the check in every action this applies too. – Andy Brudtkuhl Jan 23 '14 at 22:34
5

What you are looking for is route constraints.

Wyatt Barnett
  • 15,573
  • 3
  • 34
  • 53
  • 1
    This would mean I will be writing custom routes for a large amount of actions I have in my application as I cannot just change the generic routes, aren't there better ways to do it? – TomHastjarjanto Nov 03 '10 at 21:58
1

It's not a new article, and I can't promise that there's no better way to do it in the recent MVC builds, but I think this is a pretty good possibility :)

I believe you should be able to write a custom model binder, that will check if the ID property is present and is required, and throw a 404 error / refuse to bind if it's not there.. I know it's not much, but it might lead you in the right way :)

P.S. An example model binder + how it works can be found here:
http://weblogs.asp.net/melvynharbour/archive/2008/11/21/mvc-modelbinder-and-localization.aspx

Artiom Chilaru
  • 11,811
  • 4
  • 41
  • 52