Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically throw 404 errors when missing parameters for asp.net mvc

Tags:

c#

asp.net-mvc

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.

like image 516
TomHastjarjanto Avatar asked Nov 03 '10 21:11

TomHastjarjanto


People also ask

How to handle 404 error in asp net?

A simple solution is to check for the HTTP status code 404 in the response. If found, you can redirect the control to a page that exists. The following code snippet illustrates how you can write the necessary code in the Configure method of the Startup class to redirect to the home page if a 404 error has occurred.


1 Answers

public ActionResult Index(int? id)
{
   if(!id.HasValue())
   {
     throw new HttpException(404, "Are you sure you're in the right place?");
   }
}
like image 132
moshjeier Avatar answered Oct 12 '22 23:10

moshjeier