I am trying to setup .NET ProblemDetails Service
I have following code in 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();
Than I have simple endpoint throwing an exception
[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);
}
I switched environment variable to production and when I hit the endpoint in browser I am getting the following response
{"type":"https://tools.ietf.org/html/rfc7231#section-6.6.1","title":"An error occurred while processing your request.","status":500}
Why I do not see trace-id or request-id identifier? How to enhance the response?
The following code solved the issue and it seems to work.
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));
}
}
);
Response
{
"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"
}