Search code examples
c#asp.net-web-apiactionfilterattributedelegatinghandler

Capture all requests to Web Api 2.0, regardless that are mapped or not


I have a Web API 2.0 running at localhost:4512 and I want to intercept all requests made to domain localhost:4512 regardless if they are handled by a specific route or not. For instance I want to capture requests made to localhost:4512/abc.dfsada or localhost:4512/meh/abc.js

I have tried this with a DelegatingHandler but unfortunately this only intercepts requests made to handled routes:

public class ProxyHandler : DelegatingHandler
{
    private async Task<HttpResponseMessage> RedirectRequest(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var redirectLocation = "http://localhost:54957/";
        var localPath = request.RequestUri.LocalPath;
        var client = new HttpClient();
        var clonedRequest = await request.Clone();
        clonedRequest.RequestUri = new Uri(redirectLocation + localPath);

        return await client.SendAsync(clonedRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return RedirectRequest(request, cancellationToken);
    }
}

and in WebConfig.cs:

 config.MessageHandlers.Add(new ProxyHandler());
 config.MapHttpAttributeRoutes();
 config.Routes.MapHttpRoute(
      name: "DefaultApi",
      routeTemplate: "api/{controller}/{id}",
      defaults: new {id = RouteParameter.Optional});

Solution

  • You can use the Application_BeginRequest method in the Global.asax class. It will be invoked first when the application recieves a request

    Here's an example:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var request = ((System.Web.HttpApplication) sender).Request;
    }