asp.net ProblemDetails响应不包含TraceId属性

xt0899hw  于 2023-08-08  发布在  .NET
关注(0)|答案(1)|浏览(145)

我正在尝试安装.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标识符?如何增强应对能力?

v8wbuo2f

v8wbuo2f1#

下面的代码解决了这个问题,它似乎工作。

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));
        }
    }
);

字符串
React

{"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"}

相关问题