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.
This happens because
TypedResult.BadRequest<TValue>accepts parameter ofTValue? errorwhich as the docs say:So it does exactly what it claims to - serializes the provided value as JSON response body, hence the
helloyou see as the response. If you try something like:Then you will get accordingly:
Also you can try using
TypedResults.Problem(check out parameters you can pass to it):Which produces the following JSON body: