C# ASP.Net核心Web API捕获HTTP请求以进行日志记录

C# ASP.Net核心Web API捕获HTTP请求以进行日志记录,c#,asp.net-core,.net-core,asp.net-core-webapi,C#,Asp.net Core,.net Core,Asp.net Core Webapi,我很难在ASP.NET核心Web API中捕获用于日志记录的HTTP请求。我在这里找到了一个例子 这很有帮助。它基本上是一个日志类,使用中间件功能添加到HTTP请求管道中。问题是类方法只在应用程序启动时被调用。我无法在任何get或post http请求上调用它。get或post http请求正在工作,因为我可以调试,并且响应正常,我尝试在控制台应用程序中使用Fiddler和http客户端 这是我的日志课程 using Microsoft.AspNetCore.Http; using Micr

我很难在ASP.NET核心Web API中捕获用于日志记录的HTTP请求。我在这里找到了一个例子

这很有帮助。它基本上是一个日志类,使用中间件功能添加到HTTP请求管道中。问题是类方法只在应用程序启动时被调用。我无法在任何get或post http请求上调用它。get或post http请求正在工作,因为我可以调试,并且响应正常,我尝试在控制台应用程序中使用Fiddler和http客户端

这是我的日志课程

using Microsoft.AspNetCore.Http; 
using Microsoft.Extensions.Logging; 
using System; 
using System.Collections.Generic; 
using System.Diagnostics; 
using System.Linq; 
using System.Threading.Tasks; 


namespace CoreWebAPI.Models 
{ 
public class RequestLoggingMiddleware 
{ 
    private readonly RequestDelegate _next; 
    private readonly ILogger<RequestLoggingMiddleware> _logger; 


    public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger) 
    { 
        _next = next; 
        _logger = logger; 
    } 


    public async Task Invoke(HttpContext context) 
    { 
        var startTime = DateTime.UtcNow; 


        var watch = Stopwatch.StartNew(); 
        await _next.Invoke(context); 
        watch.Stop(); 


        var logTemplate = @" 
Client IP: {clientIP} 
Request path: {requestPath} 
Request content type: {requestContentType} 
Request content length: {requestContentLength} 
Start time: {startTime} 
Duration: {duration}"; 


        _logger.LogInformation(logTemplate, 
            context.Connection.RemoteIpAddress.ToString(), 
            context.Request.Path, 
            context.Request.ContentType, 
            context.Request.ContentLength, 
            startTime, 
            watch.ElapsedMilliseconds); 
    } 
} 
} 
使用Microsoft.AspNetCore.Http;
使用Microsoft.Extensions.Logging;
使用制度;
使用System.Collections.Generic;
使用系统诊断;
使用System.Linq;
使用System.Threading.Tasks;
命名空间CoreWebAPI.Models
{ 
公共类RequestLogging中间件
{ 
private readonly RequestDelegate\u next;
专用只读ILogger\u记录器;
公共RequestLoggingMiddleware(RequestDelegate下一步,ILogger记录器)
{ 
_下一个=下一个;
_记录器=记录器;
} 
公共异步任务调用(HttpContext上下文)
{ 
var startTime=DateTime.UtcNow;
var watch=Stopwatch.StartNew();
wait_next.Invoke(上下文);
看,停;
var logTemplate=@”
客户端IP:{clientIP}
请求路径:{requestPath}
请求内容类型:{requestContentType}
请求内容长度:{requestContentLength}
开始时间:{startTime}
持续时间:{Duration}”;
_logger.LogInformation(日志模板,
context.Connection.RemoteIpAddress.ToString(),
context.Request.Path,
context.Request.ContentType,
context.Request.ContentLength,
开始的时候,
手表。延时百万秒);
} 
} 
} 
这是我的Startup.cs类中的Startup.Configure方法

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
        loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
        loggerFactory.AddDebug(); 




        app.UseApplicationInsightsRequestTelemetry(); 


        app.UseApplicationInsightsExceptionTelemetry(); 


        app.UseMvc(); 
        app.UseCors(builder => builder.AllowAnyOrigin()); 


        app.UseMiddleware<RequestLoggingMiddleware>(); 

    }
public void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、iLogger工厂)
{ 
loggerFactory.AddConsole(Configuration.GetSection(“Logging”);
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseMvc();
app.UseCors(builder=>builder.AllowAnyOrigin());
app.UseMiddleware();
}

最后一行是我使用app.usembiddleware返回HTTP请求的地方。我认为这应该行得通,但如果有人知道为什么不行,或者有其他选择,那就太好了。请让我知道您是否应该提供其他信息。

中间件是以管道的形式调用的,按照它们注册的顺序,并且它们都决定是否应该调用下一个中间件(请参阅您自己的日志中间件:
wait _next.invoke(context);

当一个由Mvc框架处理的请求传入时,它将不会传递给下一个中间件


要对所有请求进行日志记录,您需要将日志记录的注册放在终止管道的任何中间件(如Mvc)之前。

这将很好地工作

public async Task Invoke(HttpContext context)
{
    var timer = new Stopwatch();
    timer.Start();
    await _next(context);

    //Need to stop the timer after the pipeline finish
    timer.Stop();
    _logger.LogDebug("The request took '{0}' ms", timerer.ElapsedMilliseconds);
}
在启动时,您需要在管道的开头添加中间件

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{ 
    loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
    loggerFactory.AddDebug(); 

    app.UseMiddleware<RequestLoggingMiddleware>();

    // rest of the middlewares 
      ..................

    app.UseMvc(); 
}
public void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、iLogger工厂)
{ 
loggerFactory.AddConsole(Configuration.GetSection(“Logging”);
loggerFactory.AddDebug();
app.UseMiddleware();
//其余的中间产品
..................
app.UseMvc();
}

本博客涵盖了您需要的内容: