如果 ModelStats 无效,则添加日志记录

Add logging if ModelStats is invalid

我们正在使用 InvalidModelStateResponseFactory 来标准化错误响应的布局。这很好用。

services.Configure<ApiBehaviorOptions>(options =>
{                
    options.InvalidModelStateResponseFactory = context =>
    {
       var result = new BadRequestObjectResult(new BadRequestErrorResponse(context.ModelState));
       return result;
    };
});

但现在需要记录这些错误。我们该怎么做?将 ILogger 添加到这部分代码或创建自定义 Middleware/ActionFilter?

附加信息,我们使用 Seriloger:

public static void Main(string[] args)
{
    // The initial "bootstrap" logger is able to log errors during start-up. It's completely replaced by the
    // logger configured in `UseSerilog()` below, once configuration and dependency-injection have both been
    // set up successfully.
    Log.Logger = new LoggerConfiguration()
        .WriteTo.Console()
        .CreateBootstrapLogger();

为简洁起见省略了其余部分

public static IHostBuilder CreateHostBuilder(string[] args)
{
    return Host.CreateDefaultBuilder(args)
        .UseSerilog((context, services, configuration) => configuration
            .ReadFrom.Configuration(context.Configuration)
            .ReadFrom.Services(services)
            .Enrich.FromLogContext()
        )
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });
}

您可以像这样通过context:

检索注册的记录器
var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger>();

更新#1 UseSeriLog registers an ILoggerFactory 而不是明确的 ILogger.

在这种情况下,您必须像这样修改上面的代码:

var factory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
var logger = factory.CreateLogger("InvalidModelState");