I wanted to create a custom route configuration that looks something like this:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{location}/{id}",
defaults: new { id = RouteParameter.Optional }
I need to have a location
attribute which will contain an integer id denoting the location of a specific API user.
After that, I will be putting a custom attribute at the controller level, something like:
[VerifyLocation]
public class SomeController : ApiController
which does some background validation for the location value passed to every endpoint. This means I need to be able to get the integer value of the location
attribute.
I am aware that you could use the Route
attribute to customize your routes, but the thing is want to do this without having to put in a [Route("api/{location:id}/{id:int"}]
on all my end points.
How do I go about doing this?
(In case someone stumbles upon this question)
One approach is through an ActionFilterAttribute
:
public class VerifyLocation : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var routeData = actionContext.RequestContext.RouteData;
var location = routeData.Values["location"];
// Do your thing here
base.OnActionExecuting(actionContext);
}
}