Intercept all WebApi calls before the route matching occurs

asp.net web api log all requests
web api add request header
c# intercept http request
web api log raw request
httprequestmessage web api example
httphandler c# web api
web api handler mapping
actionfilterattribute web api

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).

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

How to intercept all incoming requests with WebAPI – irhadbabic.com, How to intercept all incoming requests with WebAPI var x = "This is my custom line of code I need executed before any of the It works ONLY for requests, more specifically the ones that have an actual route; It's clean and  MeTitus. Software engineer - Motorsports 8 web api get route template from inside handler Aug 9 '14. 8 Intercept all WebApi calls before the route matching occurs

I'm using mentioned technique to log all requests and responses. Speaking shortly, the best way to do it is to use Handlers.

First, create handler:

public class CustomHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        //get route values and process them
        var routeValues = (IHttpRouteData[]) HttpContext.Current.Request.RequestContext.RouteData.Values["MS_SubRoutes"];

        //let other handlers process the request
        return await base.SendAsync(request, cancellationToken)
            .ContinueWith(task =>
            {
                //once response is ready, do something with it                                        

                return task.Result;
            }, cancellationToken);
    }
}

Then, register it in WebApiConfig:

config.MessageHandlers.Add(new CustomHandler());

Routing in ASP.NET Core, NET Core routing is responsible for matching HTTP requests and Usually middleware that appears before routing modifies some property of the request, such as See catch-all in the Route template reference for important Can be used as a prefix to a route parameter to bind to the rest of the URI. ActionFilterAttribute expose the method OnActionExecuting(), it occurs before the controller's action method is invoked. All we need to do is create a class derived from ActionAttributeFilter and override method OnActionExecuting().

Would it work to create a HttpHandler (or do it just in Global asax Application_BeginRequest event) to capture the requests and inside the handler parse the URL against route config, similar to this link.

Routing to controller actions in ASP.NET Core, If you're primarily interested in routing for REST APIs, jump to the Attribute routing Call MapControllers inside UseEndpoints to map attribute routed controllers. Matches from a route that appears earlier have a higher priority. A catch-all parameter may match routes incorrectly due to a bug in routing. The purpose of this article is to show a method for “how to intercept Web Service calls and show in screen”. We will work directly on the Worker process. Unfortunately, with sniffers, we can’t get traffic from localhost. OK, let’s start: Suppose you have an application which is calling a WebService. Open Windows Debugger: windbg.exe

Like Joel Etherton mentioned in the comments, I think what you are looking for is something like adding the following code in your global.asax:

protected void Application_EndRequest()
{
    /*
    if(HttpContext.Current.Response.StatusCode == 404)
        Debug.WriteLine("404 something something")
    if(HttpContext.Current.Response.StatusCode == 500)
        Debug.WriteLine("500 something something")
    if(HttpContext.Current.Response.StatusCode == 200)
        Debug.WriteLine("200 something something")
    */
    Debug.WriteLine($"{context.Response.StatusCode} - {request.Url.PathAndQuery}");
}

I got my inspiration from here: ASP.NET MVC 404 Error Handling

12. Controllers and Routing, Controllers and Routing Knowing how home plumbing works is unnecessary much of the NET Web API as a result, is to process HTTP requests and provide This process of calling the inner handler's SendAsync method continues until the Using the controller name, look for a matching HttpControllerDescriptor in its  Thanks for looking! Background. I am writing an API layer for a company that will be used by disparate apps and external consumers. On the consumption end, most consumers will call a service via ajax using a jQuery $.post(); however, Internet Explorer makes our lives more challenging (of course!).

Handling Bad URLs in ASP.NET MVC -- Visual Studio Magazine, I don't know how often these kinds of errors occur in production sites. to avoid breaking any existing bookmarks/calls from other applications. NET Web API of prefixing all service URLs with "api" is an example of Fortunately, of the three kinds of URL-related errors, handling a non-matching route is  Here we use onBeforeRequest to call the logURL() function just before starting the request. The logURL() function grabs the URL of the request from the event object and logs it to the browser console. The {urls: ["<all_urls>"]} pattern means we will intercept HTTP requests to all URLs.

Attribute Routing in Web API v2 - Simple Talk, Attribute routing is not a feature that Web API inherits from ASP. Any time a request comes in, the URL is matched against the template of registered routes. Most specific routes should appear first in the list; catch-all and most route is evaluated individually in the order it appears until a match is found. 8 web api get route template from inside handler 8 Intercept all WebApi calls before the route matching occurs 6 Overloaded versions of WriteLine; why not use generics/template?

The ASP.NET Web API 2 HTTP Message Lifecycle in 43 Easy Steps, Further, it doesn't explicitly tell you exactly how many things happen NET Web API 2 Request Lifecycle in just 43 easy steps! HttpRoutingDispatcher chooses which routing handler to call based on the matching route. sent (e.g. intercept certain responses and change to the appropriate HTTP status). A catch-all parameter may match routes incorrectly due to a bug in routing. Apps impacted by this bug have the following characteristics: A catch-all route, for example, {**slug}" The catch-all route fails to match requests it should match. Removing other routes makes catch-all route start working.

Comments
  • You might look into Application_BeginRequest in the global.asax.
  • I am looking for a way to intercept/grab the request being made before matching to a route -- action filters occur after a route has been matched, no? It may also be the case that the question is just not clear enough to provide a proper answer
  • If that is what you want you can use message handler, what is it you need to do before the route is discovered?
  • I'm just quoting a part of the question from the OP because I think your answer may have missed that aspect of it :)
  • Perhaps I misspoke saying before the match happens. What I mean is before the method that is matched on is called. In this case I was able to use 'OnActionExecuting' in order to hit that block of code before the method within the controller is called. This is exactly what was needed, and looked to be the overall best solution for me
  • For most of the cases action filter are fine, glad I could help :-)
  • If you use delegate handlers to log all the requests you will also log invalid requests, if all you need is to logging you should use action filters not handlers.
  • @Marco those ones interested me too :)
  • Both of them allow you to log your requests, but with action filters is easier for you to log only meaningful data :)
  • You have better ways of achieving this with what the Web API provides.