5

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});
Tamas Ionut
  • 4,240
  • 5
  • 36
  • 59

2 Answers2

3

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;
}
Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69
  • This works great! Is there a way to do some processing there and return a response if some conditions are met? - to not send the request further in the pipeline? – Tamas Ionut Jun 07 '18 at 22:09
  • However, making a GET request to http://localhost:54957/app.js does not get handled by Application_BeginRequest. Is there any way to intercept those requests as well? – Tamas Ionut Jun 08 '18 at 02:17
  • @TamasIonut ok, by default requests of static files is not included. Check this answer for solution https://stackoverflow.com/questions/27940320/capture-request-static-file-in-asp-net – Marcus Höglund Jun 08 '18 at 05:29
2

I found that the best way to do what you want to do is by using the middleware to intercept all the request and responses.

public class RequestResponseLoggingMiddleware
{
    private readonly RequestDelegate _next;

    public RequestResponseLoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        //First, get the incoming request
        var request = await FormatRequest(context.Request);

        //Copy a pointer to the original response body stream
        var originalBodyStream = context.Response.Body;

        //Create a new memory stream...
        using (var responseBody = new MemoryStream())
        {
            //...and use that for the temporary response body
            context.Response.Body = responseBody;

            //Continue down the Middleware pipeline, eventually returning to this class
            await _next(context);

            //Format the response from the server
            var response = await FormatResponse(context.Response);

            //TODO: Save log to chosen datastore

            //Copy the contents of the new memory stream (which contains the response) to the original stream, which is then returned to the client.
            await responseBody.CopyToAsync(originalBodyStream);
        }
    }

    private async Task<string> FormatRequest(HttpRequest request)
    {
        var body = request.Body;

        //This line allows us to set the reader for the request back at the beginning of its stream.
        request.EnableRewind();

        //We now need to read the request stream.  First, we create a new byte[] with the same length as the request stream...
        var buffer = new byte[Convert.ToInt32(request.ContentLength)];

        //...Then we copy the entire request stream into the new buffer.
        await request.Body.ReadAsync(buffer, 0, buffer.Length);

        //We convert the byte[] into a string using UTF8 encoding...
        var bodyAsText = Encoding.UTF8.GetString(buffer);

        //..and finally, assign the read body back to the request body, which is allowed because of EnableRewind()
        request.Body = body;

        return $"{request.Scheme} {request.Host}{request.Path} {request.QueryString} {bodyAsText}";
    }

    private async Task<string> FormatResponse(HttpResponse response)
    {
        //We need to read the response stream from the beginning...
        response.Body.Seek(0, SeekOrigin.Begin);

        //...and copy it into a string
        string text = await new StreamReader(response.Body).ReadToEndAsync();

        //We need to reset the reader for the response so that the client can read it.
        response.Body.Seek(0, SeekOrigin.Begin);

        //Return the string for the response, including the status code (e.g. 200, 404, 401, etc.)
        return $"{response.StatusCode}: {text}";
    }

Don't forget to use the middleware in the startup.cs

 public void Configure(IApplicationBuilder app, IHostingEnvironment env )
    {

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }
        app.UseMiddleware<RequestResponseLoggingMiddleware>();
        app.UseHttpsRedirection();
        app.UseMvc();
    }
mavi
  • 1,074
  • 2
  • 15
  • 29