捕获对 Web Api 2.0 的所有请求,无论是否已映射

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

我在 localhost:4512 有一个 Web API 2.0 运行,我想拦截对域 localhost:4512 发出的所有请求,无论它们是否由特定路由处理或不。 例如,我想捕获对 localhost:4512/abc.dfsadalocalhost:4512/meh/abc.js

的请求

我已经用 DelegatingHandler 尝试过,但是 unfortunately 这只会拦截对已处理路由的请求:

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);
    }
}

并在 WebConfig.cs 中:

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

可以在Global.asaxclass中使用Application_BeginRequest方法。当应用程序收到请求时,它将首先被调用

这是一个例子:

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

我发现做你想做的最好的方法是使用中间件来拦截所有的请求和响应。

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}";
    }

不要忘记使用 startup.cs

中的中间件
 public void Configure(IApplicationBuilder app, IHostingEnvironment env )
    {

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }
        app.UseMiddleware<RequestResponseLoggingMiddleware>();
        app.UseHttpsRedirection();
        app.UseMvc();
    }