ProblemDetails 响应不包含 TraceId 属性

ProblemDetails response does not contain TraceId property

提问人:Muflix 提问时间:7/12/2023 更新时间:7/12/2023 访问量:209

问:

我正在尝试设置 .NET ProblemDetails 服务

我在 Program.cs 中有以下代码

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddProblemDetails();
builder.Services.AddControllersWithViews();

var app = builder.Build();

// ProblemDetails related middlewares
app.UseExceptionHandler();
app.UseStatusCodePages();

比我有简单的端点抛出异常

[Route("api/suppliers")]
public IActionResult Get()
{
     var x = 0;
     var y = 1 / x; // throws divide by zero exception
     var suppliers = _context.Suppliers.ToList();
     return Ok(suppliers);
}

我将环境变量切换到生产环境,当我在浏览器中点击端点时,我得到以下响应

{"type":"https://tools.ietf.org/html/rfc7231#section-6.6.1","title":"An error occurred while processing your request.","status":500}

为什么我没有看到 trace-idrequest-id 标识符?如何增强响应?

asp.net 错误处理 .net-7.0

评论


答:

1赞 Muflix 7/12/2023 #1

以下代码解决了该问题,它似乎有效。

builder.Services.AddProblemDetails(options =>
    options.CustomizeProblemDetails = (context) =>
    {
        if (!context.ProblemDetails.Extensions.ContainsKey("traceId"))
        { 
            string? traceId = Activity.Current?.Id ?? context.HttpContext.TraceIdentifier;
            context.ProblemDetails.Extensions.Add(new KeyValuePair<string, object?>("traceId", traceId));
        }
    }
);

响应

{"type":"https://tools.ietf.org/html/rfc7231#section-6.6.1","title":"An error occurred while processing your request.","status":500,"traceId":"00-6cc3ae3a36c257be2cec5f41a765b3c9-3806c931361744ed-00"}