Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc action invalid arguments gives argumentexception 500 instead of 404

When i have a controller action like this.

public ActionResult _Files(long parentid)
        {

if you call the action from a browser without a parentid. It throws a System.ArgumentException and a 500 response

The parameters dictionary contains a null entry for parameter 'parentid' of non-nullable type 'System.Int64' for method 'System.Web.Mvc.ActionResult _Files

The action is NOT supposed to be called without a PARENTID by design. Is there a way to not throw an exception (and return 500 response back) and instead return a 400 bad request or a 404 not found ( either of which would make more sense IMO). Looking for a solution that would do this in a generic way across the webapplication ?

like image 799
MoXplod Avatar asked Mar 26 '14 20:03

MoXplod


1 Answers

I suggest you take a look at route constraints. Creating a route constraint would require an integer to be passed as the parentid and if not supplied, the route will not match and a 404 will be returned by default.

Here's an example:

routes.MapRoute(
    name: "MyController",
    url: "MyController/{parentid}",
    defaults: new { controller = "MyController", action = "Index" },
    constraints: new { parentid = @"\d+" }
);

See this article for more information on route constraints.

The only downside to this approach is that the regex does not check whether the input value is a long or something greater. However if that were a concern, you could easily create a custom route constraint that would check whether the input value could be parsed as a long.

like image 178
Joshua Avatar answered Oct 09 '22 16:10

Joshua