Enable ProblemDetailsService for TypedResults with ProblemDetails#64967
Enable ProblemDetailsService for TypedResults with ProblemDetails#64967mikekistler wants to merge 1 commit intomainfrom
Conversation
This change makes TypedResults.BadRequest<ProblemDetails> and similar result types utilize IProblemDetailsService customizations when the value is a ProblemDetails instance. Changes: - BadRequest<TValue> - Conflict<TValue> - UnprocessableEntity<TValue> - InternalServerError<TValue> - NotFound<TValue> All now check if the value is ProblemDetails and use IProblemDetailsService when available, falling back to direct JSON serialization otherwise. Added comprehensive tests to verify customizations are applied correctly.
There was a problem hiding this comment.
Pull request overview
This PR enables TypedResults.BadRequest<ProblemDetails> and similar result types to utilize IProblemDetailsService for customizations, providing consistency with TypedResults.Problem(). Previously, these result types would bypass any configured ProblemDetailsOptions.CustomizeProblemDetails customizations.
- Updated five result types to check if the value is
ProblemDetailsand useIProblemDetailsServicewhen available - Added comprehensive test coverage for
BadRequest<TValue>to verify the new behavior - Maintained backward compatibility with graceful fallback when service is not registered
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| src/Http/Http.Results/src/BadRequestOfT.cs | Added ProblemDetails detection and IProblemDetailsService integration to ExecuteAsync method |
| src/Http/Http.Results/src/ConflictOfT.cs | Added ProblemDetails detection and IProblemDetailsService integration to ExecuteAsync method |
| src/Http/Http.Results/src/InternalServerErrorOfT.cs | Added ProblemDetails detection and IProblemDetailsService integration to ExecuteAsync method |
| src/Http/Http.Results/src/NotFoundOfT.cs | Added ProblemDetails detection and IProblemDetailsService integration to ExecuteAsync method |
| src/Http/Http.Results/src/UnprocessableEntityOfT.cs | Added ProblemDetails detection and IProblemDetailsService integration to ExecuteAsync method |
| src/Http/Http.Results/test/BadRequestOfTResultTests.cs | Added six comprehensive tests covering customization, traceId injection, fallback behavior, derived types, and non-ProblemDetails types |
| [Fact] | ||
| public async Task BadRequestObjectResult_WithProblemDetails_UsesDefaultsFromProblemDetailsService() | ||
| { | ||
| // Arrange | ||
| var details = new ProblemDetails(); | ||
| var result = new BadRequest<ProblemDetails>(details); | ||
| var stream = new MemoryStream(); | ||
| var services = CreateServiceCollection() | ||
| .AddProblemDetails(options => options.CustomizeProblemDetails = context => context.ProblemDetails.Extensions["customProperty"] = "customValue") | ||
| .BuildServiceProvider(); | ||
| var httpContext = new DefaultHttpContext() | ||
| { | ||
| RequestServices = services, | ||
| Response = | ||
| { | ||
| Body = stream, | ||
| }, | ||
| }; | ||
|
|
||
| // Act | ||
| await result.ExecuteAsync(httpContext); | ||
|
|
||
| // Assert | ||
| Assert.Equal(StatusCodes.Status400BadRequest, httpContext.Response.StatusCode); | ||
| stream.Position = 0; | ||
| var responseDetails = System.Text.Json.JsonSerializer.Deserialize<ProblemDetails>(stream, new System.Text.Json.JsonSerializerOptions(System.Text.Json.JsonSerializerDefaults.Web)); | ||
| Assert.NotNull(responseDetails); | ||
| Assert.Equal(StatusCodes.Status400BadRequest, responseDetails.Status); | ||
| Assert.True(responseDetails.Extensions.ContainsKey("customProperty")); | ||
| Assert.Equal("customValue", responseDetails.Extensions["customProperty"]?.ToString()); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task BadRequestObjectResult_WithProblemDetails_AppliesTraceIdFromService() | ||
| { | ||
| // Arrange | ||
| var details = new ProblemDetails(); | ||
| var result = new BadRequest<ProblemDetails>(details); | ||
| var stream = new MemoryStream(); | ||
| var services = CreateServiceCollection() | ||
| .AddProblemDetails() | ||
| .BuildServiceProvider(); | ||
| var httpContext = new DefaultHttpContext() | ||
| { | ||
| RequestServices = services, | ||
| Response = | ||
| { | ||
| Body = stream, | ||
| }, | ||
| }; | ||
|
|
||
| // Act | ||
| await result.ExecuteAsync(httpContext); | ||
|
|
||
| // Assert | ||
| Assert.Equal(StatusCodes.Status400BadRequest, httpContext.Response.StatusCode); | ||
| stream.Position = 0; | ||
| var responseDetails = System.Text.Json.JsonSerializer.Deserialize<ProblemDetails>(stream, new System.Text.Json.JsonSerializerOptions(System.Text.Json.JsonSerializerDefaults.Web)); | ||
| Assert.NotNull(responseDetails); | ||
| Assert.True(responseDetails.Extensions.ContainsKey("traceId")); | ||
| Assert.NotNull(responseDetails.Extensions["traceId"]); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task BadRequestObjectResult_WithProblemDetails_FallsBackWhenServiceNotRegistered() | ||
| { | ||
| // Arrange | ||
| var details = new ProblemDetails { Title = "Test Error" }; | ||
| var result = new BadRequest<ProblemDetails>(details); | ||
| var stream = new MemoryStream(); | ||
| var httpContext = new DefaultHttpContext() | ||
| { | ||
| RequestServices = CreateServices(), | ||
| Response = | ||
| { | ||
| Body = stream, | ||
| }, | ||
| }; | ||
|
|
||
| // Act | ||
| await result.ExecuteAsync(httpContext); | ||
|
|
||
| // Assert | ||
| Assert.Equal(StatusCodes.Status400BadRequest, httpContext.Response.StatusCode); | ||
| stream.Position = 0; | ||
| var responseDetails = System.Text.Json.JsonSerializer.Deserialize<ProblemDetails>(stream, new System.Text.Json.JsonSerializerOptions(System.Text.Json.JsonSerializerDefaults.Web)); | ||
| Assert.NotNull(responseDetails); | ||
| Assert.Equal("Test Error", responseDetails.Title); | ||
| Assert.Equal(StatusCodes.Status400BadRequest, responseDetails.Status); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task BadRequestObjectResult_WithHttpValidationProblemDetails_UsesDefaultsFromProblemDetailsService() | ||
| { | ||
| // Arrange | ||
| var details = new HttpValidationProblemDetails(); | ||
| var result = new BadRequest<HttpValidationProblemDetails>(details); | ||
| var stream = new MemoryStream(); | ||
| var services = CreateServiceCollection() | ||
| .AddProblemDetails(options => options.CustomizeProblemDetails = context => context.ProblemDetails.Extensions["customValidation"] = "applied") | ||
| .BuildServiceProvider(); | ||
| var httpContext = new DefaultHttpContext() | ||
| { | ||
| RequestServices = services, | ||
| Response = | ||
| { | ||
| Body = stream, | ||
| }, | ||
| }; | ||
|
|
||
| // Act | ||
| await result.ExecuteAsync(httpContext); | ||
|
|
||
| // Assert | ||
| Assert.Equal(StatusCodes.Status400BadRequest, httpContext.Response.StatusCode); | ||
| stream.Position = 0; | ||
| var responseDetails = System.Text.Json.JsonSerializer.Deserialize<HttpValidationProblemDetails>(stream, new System.Text.Json.JsonSerializerOptions(System.Text.Json.JsonSerializerDefaults.Web)); | ||
| Assert.NotNull(responseDetails); | ||
| Assert.True(responseDetails.Extensions.ContainsKey("customValidation")); | ||
| Assert.Equal("applied", responseDetails.Extensions["customValidation"]?.ToString()); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task BadRequestObjectResult_WithNonProblemDetails_DoesNotUseProblemDetailsService() | ||
| { | ||
| // Arrange | ||
| var details = new { error = "test error" }; | ||
| var result = new BadRequest<object>(details); | ||
| var stream = new MemoryStream(); | ||
| var customizationCalled = false; | ||
| var services = CreateServiceCollection() | ||
| .AddProblemDetails(options => options.CustomizeProblemDetails = context => customizationCalled = true) | ||
| .BuildServiceProvider(); | ||
| var httpContext = new DefaultHttpContext() | ||
| { | ||
| RequestServices = services, | ||
| Response = | ||
| { | ||
| Body = stream, | ||
| }, | ||
| }; | ||
|
|
||
| // Act | ||
| await result.ExecuteAsync(httpContext); | ||
|
|
||
| // Assert | ||
| Assert.False(customizationCalled, "CustomizeProblemDetails should not be called for non-ProblemDetails types"); | ||
| Assert.Equal(StatusCodes.Status400BadRequest, httpContext.Response.StatusCode); | ||
| } | ||
|
|
||
| private static ServiceCollection CreateServiceCollection() | ||
| { | ||
| var services = new ServiceCollection(); | ||
| services.AddSingleton<ILoggerFactory, NullLoggerFactory>(); | ||
| return services; | ||
| } | ||
|
|
There was a problem hiding this comment.
Comprehensive test coverage has been added for BadRequest, but similar tests are missing for the other result types that received the same implementation changes (Conflict, NotFound, InternalServerError, and UnprocessableEntity). These test cases should be duplicated for those result types to ensure consistent behavior and catch any regressions.
There was a problem hiding this comment.
@copilot Please add tests for the other result types.
|
This PR got me thinking, could this be done via an EndpointFilter so it can be opt-in for Minimal Api's? All the results implement This removes the need for special cases within the existing Results which could be giving surprises to people. (As the ProblemDetails do not get past the HttpJsonOptions anymore). Edit: |
| // This enables customizations via ProblemDetailsOptions.CustomizeProblemDetails | ||
| if (Value is ProblemDetails problemDetails) | ||
| { | ||
| var problemDetailsService = httpContext.RequestServices.GetService<IProblemDetailsService>(); |
There was a problem hiding this comment.
The typical pattern we use here is something like:
if (problemDetailsService is null || !await problemDetailsService.TryWriteAsync(new() { HttpContext = httpContext, ProblemDetails = ProblemDetails }))
{
await HttpResultsHelper.WriteResultAsJsonAsync(
httpContext,
logger,
value: ProblemDetails,
ContentType);
}
See https://github.com/dotnet/aspnetcore/blob/main/src/Http/Http.Results/src/ProblemHttpResult.cs for an example.
There was a problem hiding this comment.
@copilot Please adopt the patterm that @captainsafia shows here.
captainsafia
left a comment
There was a problem hiding this comment.
This looks good with a small structural tweak.
I guess the other thing that remains is if there are other special return types that we want to add this to but we can start here.
Test coverage can also be updated to include the other result types (Conflict, and InternalServerError and so forth).
|
@mikekistler I've opened a new pull request, #65099, to work on those changes. Once the pull request is ready, I'll request review from you. |
|
@mikekistler I've opened a new pull request, #65114, to work on those changes. Once the pull request is ready, I'll request review from you. |
|
Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime. |
Summary
This PR makes
TypedResults.BadRequest<ProblemDetails>and similar result types utilizeIProblemDetailsServicecustomizations when the value is aProblemDetailsinstance, providing consistency withProblemHttpResultandValidationProblem.Motivation
Previously,
TypedResults.BadRequest<ProblemDetails>()would directly serialize the ProblemDetails to JSON, bypassing any customizations configured viaProblemDetailsOptions.CustomizeProblemDetails. This was inconsistent withTypedResults.Problem()which already uses the ProblemDetailsService.This inconsistency meant developers couldn't apply global customizations (like adding traceId, environment info, or custom properties) to ProblemDetails returned via
BadRequest<ProblemDetails>and similar result types.Changes
Updated the following result types to use
IProblemDetailsServicewhen the value is aProblemDetailstype:Implementation Pattern
Each result type now follows this pattern in
ExecuteAsync:Tests
Added comprehensive test coverage in
BadRequestOfTResultTests.cs:Example Usage
Benefits
✅ Consistency - All ProblemDetails results now use the same customization mechanism
✅ Flexibility - Developers can customize problem details in one place
✅ Automatic Features - TraceId injection and other standard customizations work everywhere
✅ Backward Compatible - Gracefully falls back when service not registered
✅ No Breaking Changes - Existing behavior preserved; this is purely an enhancement
Checklist