Skip to content

Missing required fields generates a 500 server error when using ExceptionHandler middleware #62311

Open
@marcominerva

Description

@marcominerva

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

I have the following code:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddProblemDetails();
builder.Services.AddOpenApi();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseExceptionHandler();

app.MapOpenApi();

app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/openapi/v1.json", app.Environment.ApplicationName);
});

app.MapPost("/api/todo", (Todo todo) =>
{
    return TypedResults.Ok();
});

app.Run();

public class Todo
{
    public int Id { get; set; }

    public required string Title { get; set; }
}

In particular, I have a model with a required field and I'm using the ExceptionHandler middleware. If I call the /api/todo endpoint without specifing the title property, I get the following 500 response:

{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.6.1",
  "title": "An error occurred while processing your request.",
  "status": 500,
  "traceId": "00-4d65c5386eeadff3b982d4aea022566a-7fdce82330733766-00"
}

However, when I comment out the app.UseExceptionHandler line, I receive a 400 error:

{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
  "title": "Microsoft.AspNetCore.Http.BadHttpRequestException",
  "status": 400,
  "detail": "Failed to read parameter \"Todo todo\" from the request body as JSON.",
  "exception": {
    "details": "Microsoft.AspNetCore.Http.BadHttpRequestException: Failed to read parameter \"Todo todo\" from the request body as JSON.\r\n ---> System.Text.Json.JsonException: JSON deserialization for type 'Todo' was missing required properties including: 'title'.\r\n   at System.Text.Json.ThrowHelper.ThrowJsonException_JsonRequiredPropertyMissing(JsonTypeInfo parent, BitArray requiredPropertiesSet)\r\n

Expected Behavior

The response status code should be the same, regardless of whether the ExceptionHandler middleware is used.

Steps To Reproduce

Minimal repro: https://github.com/marcominerva/Required500Issue

.NET Version

10.0.100-preview.5.25277.114

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etcfeature-problem-details

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions