1

I'm facing a behavior in Minimal API that I can't understand.Consider the following simple Minimal API:

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.UseExceptionHandler((exceptionApp) =>
{
    exceptionApp.Run(async context =>
    {
        context.Response.ContentType = MediaTypeNames.Text.Plain;

        var feature = context.Features.Get<IExceptionHandlerPathFeature>();
        if (feature?.Error is BadHttpRequestException ex)
        {
            context.Response.StatusCode = 400;
            var message =
                (ex.InnerException is JsonException)
                    ? "The request body is an invalid JSON"
                    : "Bad Request";
            await context.Response.WriteAsync(message);
        }
        else
        {
            context.Response.StatusCode = 500;
            await context.Response.WriteAsync("There is a problem occured");
        }
    });
});

app.MapPost("/models", (Model model) => Results.Created(string.Empty, model));

app.Run();
public record Model(int Value, string Title);

When I run the application in the Development environment, and pass an invalid JSON like

{
    "value": 1,
    "Title": Model #1
}

the custom exception handler is called and I have to control the behavior of the API. But whenever I run the application in the Production environment, the framework automatically returns a "bad request" response without letting me control the response.

Could anyone explain this behavior to me? I really need my exception handler to handle invalid input JSON exceptions.

Thanks

Farzan Hajian
  • 1,799
  • 17
  • 27

1 Answers1

2

After digging into ASP.Net Core source code for a while, I found that the following line resolves the issue.

builder.Services.Configure<RouteHandlerOptions>(o => o.ThrowOnBadRequest = true);
Farzan Hajian
  • 1,799
  • 17
  • 27