Search code examples
c#asp.net-core

I can't make ProblemDetails pattern working every time


Trying to investigate ProblemDetails and met some issues.

My code:

using Microsoft.AspNetCore.Builder;
using WebApplication3;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();
app.UseStatusCodePages();
app.UseExceptionHandler();

app.MapGet("/hello", () =>
{
    throw new Exception("Oulah. Hello API has problems!");
});

app.MapGet("/bad", () => Results.BadRequest(new
{
    message = "Very bad, you have a problem."
}));

app.Run();

As you can see there are 2 API methods - hello and bad.

My issue: I do get the expected response body with hello:

enter image description here

But with bad, it is a different story:

enter image description here

ProblemDetail is not activated.

I can't see what is different in my code than in other examples I can see.

What I need:

  1. To understand what is happening
  2. What I can do

Thank you


Solution

  • It's not auto-"activated", because your current setup converts ONLY Exceptions to Problems.

    If you had added:

    app.UseStatusCodePages()
    

    and removed the message

    app.MapGet("/bad", () => Results.BadRequest());
    

    you'd get the extra "activation" of requests 4xx-5xx with no body being converted to ProblemDetails.

    If you want to return ProblemDetails with a message you need to do it yourself:

    app.MapGet("/bad", () => 
       TypedResults.Problem(statusCode: StatusCodes.Status400BadRequest, 
       title: "Bad"));