-
-
Notifications
You must be signed in to change notification settings - Fork 0
4. Override ProblemDetails builder
Stratis Dermanoutsos edited this page Sep 18, 2025
·
5 revisions
There is one simple way to override the default ProblemDetails builder - Create your own extending our IRestExceptionProblemDetailsBuilder and register it as Singleton.
For example:
public class UserIdProblemDetailsBuilder : IRestExceptionProblemDetailsBuilder
{
public ProblemDetails Build(HttpContext httpContext, RestException restException)
{
var problemDetails = new ProblemDetails
{
Status = (int)restException.StatusCode,
Title = restException.Title,
Detail = restException.Message,
Type = $"https://www.rfc-editor.org/rfc/rfc9110.html#name-{restException.TypeSuffix}",
Extensions = new Dictionary<string, object?> {
{ "userId", httpContext.User.FindFirst("Id")?.Value ?? "-" }
}
};
return problemDetails;
}
}
public class UserIdProblemDetailsBuilder : IRestExceptionProblemDetailsBuilder
{
public ProblemDetails Build(HttpContext httpContext, RestException restException)
{
// Create default ProblemDetails
var defaultBuilder = new DefaultRestExceptionProblemDetailsBuilder();
var problemDetails = defaultBuilder.Build(httpContext, restException);
// Make modifications
problemDetails.Extensions.Add("userId", httpContext.User.FindFirst("Id")?.Value ?? "-");
return problemDetails;
}
}
References:
builder.Services.AddSingleton<IRestExceptionProblemDetailsBuilder, UserIdProblemDetailsBuilder>();
Ideally, do this before registering the middleware itself.
builder.Services.AddRestExceptions();
{
"type": "https://www.rfc-editor.org/rfc/rfc9110.html#name-404-not-found",
"title": "Not Found",
"status": 404,
"detail": "The form was not found.",
"instance": "/forms/50",
"traceId": "00-a990b43a04d5860e3e8ec0fb8d8b0f4f-a1993ba072baf468-00",
"method": "GET",
"requestId": "0HNEC3JK52NBG:00000001"
}
{
"type": "https://www.rfc-editor.org/rfc/rfc9110.html#name-404-not-found",
"title": "Message in title: The form was not found.",
"status": 404,
"detail": "Not Found",
"instance": "/forms/50",
"userId": "f038f5d2-2f4c-4e07-88f4-fff8b07045d8",
"traceId": "00-88963d8c894b42b7041b02f610c400dc-3e914fd68d9137ad-00",
"method": "GET",
"requestId": "0HNEC3LDP62CM:00000001"
}
"instance"
"method"
"requestId"
"traceId"
Copyright © Stratis Dermanoutsos 2025