Return NotFound with details
Hello. I have a asp.net core Web API with controllers and I want to return for example a NotFound Error with a custom message attached, that I can then show to the user.
This for example creates a problem, so the format that I want:
But when I add a message to the ActionResult I only get a
text/plain
message:
Does someone have an idea, what is going on?8 Replies
what's going on is that you told your API method to return a string, so that's what it did
Okay, but is there a way to convert that into a problem details?
ProblemDetails Class (Microsoft.AspNetCore.Mvc)
A machine-readable format for specifying errors in HTTP API responses based on https://tools.ietf.org/html/rfc7807.
So I'd have to create an instance of that and then return that? But it feels like a lot of boiler code to add that at every controller and for every possible response code. I just wanted a consistent error response format to for all errors, with optional details
Handle errors in ASP.NET Core web APIs
Learn about error handling with ASP.NET Core web APIs.
Thank you for the resources, I'll take a look at that 🙂
I think some of that latter section, with regards to services.AddProblemDetails() is only applicable to ASP.NET Core 7+.
if thay matters on your end
That is fine, tho I see this:
The following code configures the app to generate a problem details response for all HTTP client and server error responses that don't have a body content yet:Do have an Idea how I could still attach details? I could go ahead and create exceptions for each status code, I guess. But this still feels like a lot of boilerplate to me. And its imho something very basic so I thought there might a already build solution for this