-
Notifications
You must be signed in to change notification settings - Fork 10.3k
Enhance validation error handling in ValidationEndpointFilterFactory using IProblemDetailsService #62066
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
captainsafia
merged 5 commits into
dotnet:main
from
marcominerva:validation-problemdetails
May 29, 2025
Merged
Enhance validation error handling in ValidationEndpointFilterFactory using IProblemDetailsService #62066
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
29168ec
Enhance validation error handling in filter factory
marcominerva 3f31315
Add validation filter tests for ProblemDetails handling
marcominerva 5288c3a
Fix a typo
marcominerva 2e46d78
Enhance validation endpoint tests
marcominerva 83f30b6
Apply suggestions from code review
captainsafia File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
183 changes: 183 additions & 0 deletions
183
src/Http/Http.Extensions/test/ValidationFilterEndpointFactoryTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,183 @@ | ||
#pragma warning disable ASP0029 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. | ||
|
||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.ComponentModel.DataAnnotations; | ||
using System.Net.Mime; | ||
using System.Text.Json; | ||
using Microsoft.AspNetCore.Builder; | ||
using Microsoft.AspNetCore.InternalTesting; | ||
using Microsoft.AspNetCore.Mvc; | ||
using Microsoft.AspNetCore.Routing; | ||
using Microsoft.Extensions.DependencyInjection; | ||
|
||
namespace Microsoft.AspNetCore.Http.Extensions.Tests; | ||
|
||
public class ValidationEndpointFilterFactoryTests : LoggedTest | ||
{ | ||
[Fact] | ||
public async Task GetHttpValidationProblemDetailsWhenProblemDetailsServiceNotRegistered() | ||
{ | ||
var services = new ServiceCollection(); | ||
services.AddValidation(); | ||
var serviceProvider = services.BuildServiceProvider(); | ||
|
||
var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(serviceProvider)); | ||
|
||
// Act - Create one endpoint with validation | ||
builder.MapGet("validation-test", ([Range(5, 10)] int param) => "Validation enabled here."); | ||
|
||
// Build the endpoints | ||
var dataSource = Assert.Single(builder.DataSources); | ||
var endpoints = dataSource.Endpoints; | ||
|
||
// Get filter factories from endpoint | ||
var endpoint = endpoints[0]; | ||
|
||
var context = new DefaultHttpContext | ||
{ | ||
RequestServices = serviceProvider | ||
}; | ||
|
||
context.Request.Method = "GET"; | ||
context.Request.QueryString = new QueryString("?param=15"); | ||
using var ms = new MemoryStream(); | ||
context.Response.Body = ms; | ||
|
||
await endpoint.RequestDelegate(context); | ||
|
||
// Assert | ||
Assert.Equal(StatusCodes.Status400BadRequest, context.Response.StatusCode); | ||
Assert.StartsWith(MediaTypeNames.Application.Json, context.Response.ContentType, StringComparison.OrdinalIgnoreCase); | ||
|
||
ms.Seek(0, SeekOrigin.Begin); | ||
var problemDetails = await JsonSerializer.DeserializeAsync<ProblemDetails>(ms, JsonSerializerOptions.Web); | ||
|
||
Assert.Equal("One or more validation errors occurred.", problemDetails.Title); | ||
|
||
// Check that ProblemDetails contains the errors object with 1 validation error | ||
Assert.True(problemDetails.Extensions.TryGetValue("errors", out var errorsObj)); | ||
var errors = Assert.IsType<JsonElement>(errorsObj); | ||
Assert.True(errors.EnumerateObject().Count() == 1); | ||
} | ||
|
||
[Fact] | ||
public async Task UseProblemDetailsServiceWhenAddedInServiceCollection() | ||
{ | ||
var services = new ServiceCollection(); | ||
services.AddValidation(); | ||
services.AddProblemDetails(); | ||
var serviceProvider = services.BuildServiceProvider(); | ||
|
||
var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(serviceProvider)); | ||
|
||
// Act - Create one endpoint with validation | ||
builder.MapGet("validation-test", ([Range(5, 10)] int param) => "Validation enabled here."); | ||
|
||
// Build the endpoints | ||
var dataSource = Assert.Single(builder.DataSources); | ||
var endpoints = dataSource.Endpoints; | ||
|
||
// Get filter factories from endpoint | ||
var endpoint = endpoints[0]; | ||
|
||
var context = new DefaultHttpContext | ||
{ | ||
RequestServices = serviceProvider | ||
}; | ||
|
||
context.Request.Method = "GET"; | ||
context.Request.QueryString = new QueryString("?param=15"); | ||
using var ms = new MemoryStream(); | ||
context.Response.Body = ms; | ||
|
||
await endpoint.RequestDelegate(context); | ||
|
||
// Assert | ||
Assert.Equal(StatusCodes.Status400BadRequest, context.Response.StatusCode); | ||
Assert.StartsWith(MediaTypeNames.Application.ProblemJson, context.Response.ContentType, StringComparison.OrdinalIgnoreCase); | ||
|
||
ms.Seek(0, SeekOrigin.Begin); | ||
var problemDetails = await JsonSerializer.DeserializeAsync<ProblemDetails>(ms, JsonSerializerOptions.Web); | ||
|
||
// Check if the response is an actual ProblemDetails object | ||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.1", problemDetails.Type); | ||
Assert.Equal("One or more validation errors occurred.", problemDetails.Title); | ||
Assert.Equal(StatusCodes.Status400BadRequest, problemDetails.Status); | ||
|
||
// Check that ProblemDetails contains the errors object with 1 validation error | ||
Assert.True(problemDetails.Extensions.TryGetValue("errors", out var errorsObj)); | ||
var errors = Assert.IsType<JsonElement>(errorsObj); | ||
Assert.True(errors.EnumerateObject().Count() == 1); | ||
} | ||
|
||
[Fact] | ||
public async Task UseProblemDetailsServiceWithCallbackWhenAddedInServiceCollection() | ||
{ | ||
var services = new ServiceCollection(); | ||
services.AddValidation(); | ||
|
||
services.AddProblemDetails(options => | ||
{ | ||
options.CustomizeProblemDetails = context => | ||
{ | ||
context.ProblemDetails.Extensions.Add("timestamp", DateTimeOffset.Now); | ||
}; | ||
}); | ||
|
||
var serviceProvider = services.BuildServiceProvider(); | ||
|
||
var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(serviceProvider)); | ||
|
||
// Act - Create one endpoint with validation | ||
builder.MapGet("validation-test", ([Range(5, 10)] int param) => "Validation enabled here."); | ||
|
||
// Build the endpoints | ||
var dataSource = Assert.Single(builder.DataSources); | ||
var endpoints = dataSource.Endpoints; | ||
|
||
// Get filter factories from endpoint | ||
var endpoint = endpoints[0]; | ||
|
||
var context = new DefaultHttpContext | ||
{ | ||
RequestServices = serviceProvider | ||
}; | ||
|
||
context.Request.Method = "GET"; | ||
context.Request.QueryString = new QueryString("?param=15"); | ||
using var ms = new MemoryStream(); | ||
context.Response.Body = ms; | ||
|
||
await endpoint.RequestDelegate(context); | ||
|
||
// Assert | ||
Assert.Equal(StatusCodes.Status400BadRequest, context.Response.StatusCode); | ||
Assert.StartsWith(MediaTypeNames.Application.ProblemJson, context.Response.ContentType, StringComparison.OrdinalIgnoreCase); | ||
|
||
ms.Seek(0, SeekOrigin.Begin); | ||
var problemDetails = await JsonSerializer.DeserializeAsync<ProblemDetails>(ms, JsonSerializerOptions.Web); | ||
|
||
// Check if the response is an actual ProblemDetails object | ||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.1", problemDetails.Type); | ||
Assert.Equal("One or more validation errors occurred.", problemDetails.Title); | ||
Assert.Equal(StatusCodes.Status400BadRequest, problemDetails.Status); | ||
|
||
// Check that ProblemDetails contains the errors object with 1 validation error | ||
Assert.True(problemDetails.Extensions.TryGetValue("errors", out var errorsObj)); | ||
var errors = Assert.IsType<JsonElement>(errorsObj); | ||
Assert.True(errors.EnumerateObject().Count() == 1); | ||
|
||
// Check that ProblemDetails customizations are applied in the response | ||
Assert.True(problemDetails.Extensions.ContainsKey("timestamp")); | ||
} | ||
|
||
private class DefaultEndpointRouteBuilder(IApplicationBuilder applicationBuilder) : IEndpointRouteBuilder | ||
{ | ||
private IApplicationBuilder ApplicationBuilder { get; } = applicationBuilder ?? throw new ArgumentNullException(nameof(applicationBuilder)); | ||
public IApplicationBuilder CreateApplicationBuilder() => ApplicationBuilder.New(); | ||
public ICollection<EndpointDataSource> DataSources { get; } = []; | ||
public IServiceProvider ServiceProvider => ApplicationBuilder.ApplicationServices; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.