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 ?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With