How do I return a 404 status where invalid parameters are passed to my ASP.NET MVC controller? How do I return a 404 status where invalid parameters are passed to my ASP.NET MVC controller? asp.net asp.net

How do I return a 404 status where invalid parameters are passed to my ASP.NET MVC controller?


Best way? Action method selector attribute!

To actually avoid nullable method arguments I suggest that you write an Action Method Selector attribute that will actually only match your action method when id is supplied. It won't say that argument wasn't supplied but that it couldn't match any action methods for the given request.

I would call this action selector RequireRouteValuesAttribute and would work this way:

[RequireRouteValues("id")]public ActionResult GetAccount(int id){    ...}

Why is this the best solution for your problem?

If you look at your code you'd like to return a 404 on actions that match name but parameter binding failed (either because it wasn't supplied or any other reason). Your action so to speak requires particular action parameter otherwise a 404 is returned.

So when adding action selector attribute adds the requirement on the action so it has to match name (this is given by MVC) and also require particular action parameters. Whenever id is not supplied this action is not matched. If there's another action that does match is not the issue here because that particular action will get executed. The main thing is accomplished. Action doesn't match for invalid route request and a 404 is returned instead.

There's an app code for that!

Check my blog post that implements this kind of attribute that you can use out of the box. It does exactly what you're after: it won't match your action method if route data provided doesn't have all required values.


Disclaimer: this does not cover all the cases

For urls in your examples, returning 404 can be done in single line. Just add route constraint for id parameter.

routes.MapRoute(    "Default", // Route name    "{controller}/{action}/{id}", // URL with parameters    new { controller = "Home", action = "Index" }, // Parameter defaults    new { id = @"\d+" } // restrict id to be required and numeric);

And that's all. Now any matching url that has no id or id is not numeric, autimatically triggers not found error (for which there are plenty of ways to handle, one in your example, another by using custom HandleErrorAttribute, etc). And you can use non-nullable int parameters on your actions.


I managed to get this working by adding this route at the end of all routes:

routes.MapRoute("CatchAllErrors", "{*url}",    new { controller = "Error", action = "NotFound" });

Note: First I followed this: How can I properly handle 404 in ASP.NET MVC?