Skip to content

Commit 29168ec

Browse files
committed
Enhance validation error handling in filter factory
Modify validation error handling to utilize IProblemDetailsService for response writing. Fallback to default behavior if the service is unavailable.
1 parent c5d6996 commit 29168ec

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

src/Http/Routing/src/ValidationEndpointFilterFactory.cs

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55

66
using System.ComponentModel.DataAnnotations;
77
using System.Linq;
8+
using System.Net.Mime;
89
using System.Reflection;
10+
using Microsoft.AspNetCore.Http.HttpResults;
911
using Microsoft.AspNetCore.Http.Metadata;
1012
using Microsoft.Extensions.DependencyInjection;
1113
using Microsoft.Extensions.Options;
@@ -87,8 +89,27 @@ public static EndpointFilterDelegate Create(EndpointFilterFactoryContext context
8789
if (validateContext is { ValidationErrors.Count: > 0 })
8890
{
8991
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);
92113
}
93114

94115
return await next(context);

0 commit comments

Comments
 (0)