Skip to content

Impossible to modify ValidationProblemDetails when validation in Minimal APIs is triggered #62723

@mirekholec

Description

@mirekholec

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

When an error occurs in Minimal APIs, the CustomizeProblemDetails method is always executed, allowing customization of the ProblemDetails response. For example, this applies when an endpoint is not found or when Results.BadRequest is returned from an endpoint. However, if validation is triggered in Minimal APIs and an error occurs, the CustomizeProblemDetails method is not executed, and the error response structure cannot be customized.

builder.Services.AddProblemDetails(x=> x.CustomizeProblemDetails = (c) =>
{
    c.ProblemDetails = new ProblemDetails(){Title = "My Error"};
});

Expected Behavior

Once validation in Minimal API fails, the CustomizeProblemDetails method should be invoked so that we can modify the error structure like this:

builder.Services.AddProblemDetails(x=> x.CustomizeProblemDetails = (c) =>
{
    if (c.HttpContext.Response.StatusCode == 400)
    {
        // customize the ProblemDetails for 400 Bad Request
        c.ProblemDetails = new ValidationProblemDetails();
    }
});

Steps To Reproduce

  1. Create new project (dotnet new webapi -minimal) with .NET SDK 10 prev5
  2. Add Minimal APIs validation (builder.services.AddValidation())
  3. Create new endpoint app.MapPost("/test", (TestEntity data,) => { }
  4. Create entity TestEntity with some validation attributes
  5. Register ProblemDetails together with UseExceptionHandler and UseStatusCodePages

Example:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddProblemDetails(x=> x.CustomizeProblemDetails = (c) =>
{
     // it is not fired
});

builder.Services.AddValidation();

var app = builder.Build();

app.UseExceptionHandler();
app.UseStatusCodePages();

app.MapPost("/test", (TestEntity test) =>
{
    return Results.Ok();
});

app.Run();


public class TestEntity
{
    [Required]
    public string Title { get; set; }
}

Exceptions (if any)

No response

.NET Version

10.0.100-preview.5.25277.114

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etcfeature-validationIssues related to model validation in minimal and controller-based APIs

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions