从自定义的错误请求响应中记录

时间:2019-05-24 18:31:35

标签: asp.net-core asp.net-core-webapi asp.net-core-webapi-2.1

我正在使用下面的代码捕获模型验证错误,并从CustomProblemDetails对象输出一个自定义400响应,效果很好。我的问题是,我想从CustomProblemDetails对象中登录,但看不到如何使用DI。我已经传递了上下文,这使我可以访问服务,但这是要走的路吗?如果是这样,我只能访问ILoggerFactory,如何使用ILoggerFactory登录?

services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .ConfigureApiBehaviorOptions(options =>
    {
        options.InvalidModelStateResponseFactory = context =>
        {
            var problemDetails = new CustomProblemDetails(context)
            {
                Type = "https://contoso.com/probs/modelvalidation",
                Title = "One or more model validation errors occurred.",
                Status = StatusCodes.Status400BadRequest,
                Detail = "See the errors property for details.",
                Instance = context.HttpContext.Request.Path
            };

            return new BadRequestObjectResult(problemDetails)
            {
                ContentTypes = { "application/problem+json" }
            };
        };
    });

1 个答案:

答案 0 :(得分:0)

要登录InvalidModelStateResponseFactory,您可以尝试使用以下代码:

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).ConfigureApiBehaviorOptions(options =>
{
    options.InvalidModelStateResponseFactory = context =>
    {
        var loggerFactory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
        var logger = loggerFactory.CreateLogger("Logger From Invalid Model");
        var problemDetails = new CustomProblemDetails(context)
        {
            Type = "https://contoso.com/probs/modelvalidation",
            Title = "One or more model validation errors occurred.",
            Status = StatusCodes.Status400BadRequest,
            Detail = "See the errors property for details.",
            Instance = context.HttpContext.Request.Path
        };
        logger.LogError(JsonConvert.SerializeObject(problemDetails));
        return new BadRequestObjectResult(problemDetails)
        {
            ContentTypes = { "application/problem+json" }
        };
    };
});