I am looking for a way to intercept/grab the request being made before matching to a route. For example, I have multiple controllers and routes set up, but I want some mechanism in which will be hit before the route method is hit. It would be highly preferable if this mechanism were able to get the route params that were sent.
I have been unable to find something similar to what I am looking for (but perhaps not being well versed in Web API I am searching with the wrong keywords).
ControllerBase class Web API controllers should typically derive from ControllerBase rather from Controller. Controller derives from ControllerBase and adds support for views, so it's for handling web pages, not web API requests. If the same controller must support views and web APIs, derive from Controller .
The default route template for Web API is "api/{controller}/{id}". In this template, "api" is a literal path segment, and {controller} and {id} are placeholder variables. When the Web API framework receives an HTTP request, it tries to match the URI against one of the route templates in the routing table.
The ApiController attribute is commonly coupled with the ControllerBase class to enable REST-specific behavior for controllers, and it allows us to build HTTP APIs. First of all, it provides implicit model state validation, which means that we do not need to explicitly check the ModelState.
Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API.
What you need is action filters. You can apply action filters directly to controllers as attributes, the caveat with Action filters is that at this point the controller route is already known but you can still control (very much like AOP) if the action method can be executed or not:
ASP.NET Web API ActionFilter example
Look at how you can use an action filter, in this case for logging:
public class LogActionFilter : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
Log(actionExecutedContext.ActionContext.RequestContext.RouteData);
base.OnActionExecuted(actionExecutedContext);
}
private void Log(System.Web.Http.Routing.IHttpRouteData httpRouteData)
{
var controllerName = "controller name";
var actionName = "action name";
var message = String.Format("controller:{0}, action:{1}", controllerName, actionName);
Debug.WriteLine(message, "Action Filter Log");
}
}
How to log which action method is executed in a controller in webapi
You can also use message handlers, which are executed before the controller is resolved:
HTTP Message Handlers in ASP.NET Web API
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