如何在全球范围内跟踪 .net core 2.1 中的所有 HTTP 请求?

cen*_*ver 9 c# system.diagnostics dotnet-httpclient .net-core

我想在 dotnet core 2.1 应用程序中记录所有 HTTP 请求。日志记录应包括 HTTP 标头、正文和主机地址。我需要在不更改现有代码的情况下全局绑定我的日志记录代码。

我试过这个例子https://www.azurefromthetrenches.com/capturing-and-tracing-all-http-requests-in-c-and-net/,但没有 HTTP 事件来到监听器。

有没有办法在全球范围内侦听 dotnet core 2.1 上的 HTTP 事件?

Jac*_*man 8

这是Steve Gordon 撰写关于 HttpClient 登录 .Net Core 2.1的好博文

本质上,您需要将 System.Net.Http.HttpClient 的日志记录级别设置为 Trace 以获取有关请求和响应的详细信息。

appsettings.json 中所需部分的示例如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "System.Net.Http.HttpClient": "Trace"
    }
  }
Run Code Online (Sandbox Code Playgroud)

这将显示所有 HttpClient 请求和响应的所有跟踪日志记录。


Hun*_*ach 5

您可以在中间件中记录所有 http 请求信息。看看下面的例子

1.创建一个类 RequestHandlerMiddleware.cs

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.IO;
using System.Threading.Tasks;

namespace Onsolve.ONE.WebApi.Middlewares
{
    public sealed class RequestHandlerMiddleware
    {
        private readonly RequestDelegate next;
        private readonly ILogger logger;

        public RequestHandlerMiddleware(ILogger<RequestHandlerMiddleware> logger, RequestDelegate next)
        {
            this.next = next;
            this.logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            logger.LogInformation($"Header: {JsonConvert.SerializeObject(context.Request.Headers, Formatting.Indented)}");

            context.Request.EnableBuffering();
            var body = await new StreamReader(context.Request.Body).ReadToEndAsync();
            logger.LogInformation($"Body: {body}");
            context.Request.Body.Position = 0;

            logger.LogInformation($"Host: {context.Request.Host.Host}");
            logger.LogInformation($"Client IP: {context.Connection.RemoteIpAddress}");
            await next(context);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

2.添加RequestHandlerMiddlewareConfigure方法中Startup.cs

app.UseMiddleware<RequestHandlerMiddleware>();
Run Code Online (Sandbox Code Playgroud)

或更简单的

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger<Startup> logger)
{
    app.Use(async (context, next) =>
    {
        logger.LogInformation($"Header: {JsonConvert.SerializeObject(context.Request.Headers, Formatting.Indented)}");

        context.Request.EnableBuffering();
        var body = await new StreamReader(context.Request.Body).ReadToEndAsync();
        logger.LogInformation($"Body: {body}");
        context.Request.Body.Position = 0;

        logger.LogInformation($"Host: {context.Request.Host.Host}");
        logger.LogInformation($"Client IP: {context.Connection.RemoteIpAddress}");
        await next.Invoke();
    });
}
Run Code Online (Sandbox Code Playgroud)

参考:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.2

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-2.2