I have a publicly available controller (The action cannot be hidden under any security attribute) . The controller has an action which is available publicly as well.
Following is a sample structure of the controller :
public SomeController : Controller {
[HttpGet]
public ActionResult show(int id){
}
}
The action has a id field which is required. However throws an error which unnecessary adds to the logs when someone enters a malformed URL without the required id (or when search engine bots hit the a URL with the required id).
What should be the ideal solution to deal with this solution.
Possible solutions that come to my mind are :
Is there a generic way using Attributes to do this?
P.S : (to be specific) by explicit I mean writing if else conditions to handle such cases per controller.
I would appreciate any hints in the right direction.
You need a route constraint. This will help the router throw out URLs earlier (resulting in a 404) rather than later (the route is valid, goes to action, action barfs because a parameter is missing).
http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-a-route-constraint-cs
Example default route (potentially replacing the existing one in your global.asax.cx):
// order is important; more specific routes to less specific routes is what you want
//
// default index action, with no ID
routes.MapRoute(
"Default_Index",
"{controller}/",
new {controller="Home", action="Index"}
);
// default create action, with no ID
routes.MapRoute(
"Default_Create",
"{controller}/Create",
new {controller="Home", action="Create"}
);
// default action requiring an ID (such as EDIT)
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {controller="Home", action="Index"},
new {id = @"\d+" }
);
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