|
5 | 5 |
|
6 | 6 | using System.ComponentModel.DataAnnotations; |
7 | 7 | using System.Linq; |
| 8 | +using System.Net.Mime; |
8 | 9 | using System.Reflection; |
| 10 | +using Microsoft.AspNetCore.Http.HttpResults; |
9 | 11 | using Microsoft.AspNetCore.Http.Metadata; |
10 | 12 | using Microsoft.Extensions.DependencyInjection; |
11 | 13 | using Microsoft.Extensions.Options; |
@@ -87,8 +89,27 @@ public static EndpointFilterDelegate Create(EndpointFilterFactoryContext context |
87 | 89 | if (validateContext is { ValidationErrors.Count: > 0 }) |
88 | 90 | { |
89 | 91 | context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest; |
90 | | - context.HttpContext.Response.ContentType = "application/problem+json"; |
91 | | - return await ValueTask.FromResult(new HttpValidationProblemDetails(validateContext.ValidationErrors)); |
| 92 | + |
| 93 | + var problemDetails = new HttpValidationProblemDetails(validateContext.ValidationErrors); |
| 94 | + |
| 95 | + var problemDetailsService = context.HttpContext.RequestServices.GetService<IProblemDetailsService>(); |
| 96 | + if (problemDetailsService is not null) |
| 97 | + { |
| 98 | + if (await problemDetailsService.TryWriteAsync(new() |
| 99 | + { |
| 100 | + HttpContext = context.HttpContext, |
| 101 | + ProblemDetails = problemDetails |
| 102 | + })) |
| 103 | + { |
| 104 | + // We need to prevent further execution, because the actual |
| 105 | + // ProblemDetails response has already been written by ProblemDetailsService. |
| 106 | + return await ValueTask.FromResult(EmptyHttpResult.Instance); |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + // Fallback to the default implementation. |
| 111 | + context.HttpContext.Response.ContentType = MediaTypeNames.Application.ProblemJson; |
| 112 | + return await ValueTask.FromResult(problemDetails); |
92 | 113 | } |
93 | 114 |
|
94 | 115 | return await next(context); |
|
0 commit comments