ProblemDetails not working when returning TypedResults.BadRequest<string>

95 Views Asked by At

I have this sample of an ASP.NET Core 8 application using ProblemDetails.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddProblemDetails();
var app = builder.Build();

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

app.MapGet("/400", () => TypedResults.BadRequest());
app.MapGet("/exception", () =>
{
    throw new Exception("Exception!");
});

app.MapGet("/400/hello", () => TypedResults.BadRequest("Hello"));

app.Run();

The first two endpoints where I throw an exception or return a TypedResult.BadRequest I get a nice JSON formatted error response, like this:

{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
  "title": "Bad Request",
  "status": 400
}

However, with the third endpoint which returns a TypedResult.BadRequest<string>, I only get the string back, no JSON object. How come? I'd like to get a problem details object with the message as a details property.

1

There are 1 best solutions below

0
Guru Stron On BEST ANSWER

This happens because TypedResult.BadRequest<TValue> accepts parameter of TValue? error which as the docs say:

TValue
The type of error object that will be JSON serialized to the response body.

error TValue
The value to be included in the HTTP response body.

So it does exactly what it claims to - serializes the provided value as JSON response body, hence the hello you see as the response. If you try something like:

TypedResults.BadRequest(new {error = 1}

Then you will get accordingly:

{"error":1}

Also you can try using TypedResults.Problem (check out parameters you can pass to it):

app.MapGet("/400/hello2", () => TypedResults.Problem("hello", statusCode: 400));

Which produces the following JSON body:

{
   "type":"https://tools.ietf.org/html/rfc9110#section-15.5.1",
   "title":"Bad Request",
   "status":400,
   "detail":"hello"
}