【问题标题】:Capture all requests to Web Api 2.0, regardless that are mapped or not捕获对 Web Api 2.0 的所有请求,无论是否映射
【发布时间】:2018-06-07 19:32:59
【问题描述】:

我有一个在 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});

【问题讨论】:

  • 你在使用 Owin 吗?
  • 不,我没有使用 Owin。

标签: c# asp.net-web-api actionfilterattribute delegatinghandler


【解决方案1】:

您可以在 Global.asax 类中使用 Application_BeginRequest 方法。当应用收到请求时会首先调用它

这是一个例子:

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

【讨论】:

  • 这很好用!有没有办法在那里进行一些处理并在满足某些条件时返回响应? - 不在管道中进一步发送请求?
  • 但是,向localhost:54957/app.js 发出 GET 请求不会由 Application_BeginRequest 处理。有没有办法拦截这些请求?
  • @TamasIonut 好的,默认情况下不包括静态文件请求。检查此答案以获取解决方案stackoverflow.com/questions/27940320/…
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-20
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 2017-11-25
    • 1970-01-01
    相关资源
    最近更新 更多