Lorena Sfăt
Lorena Sfăt

Reputation: 235

Minimal API return result with StatusCode and Problem

The convention in our microservices is to return the result as follows:

    return result.StatusCode == (int) HttpStatusCode.Created
        ? StatusCode(result.StatusCode, result.MessageCode)
        : Problem(result.MessageCode, statusCode:result.StatusCode);

So making use of the StatusCode and Problem in Microsoft.AspNetCore.Mvc class ControllerBase.

We're adding a new microservice and figured we'd try to implement it as a Minimal API. Is there an equivalent for the Minimal API that follows the same structure?

Upvotes: 1

Views: 3498

Answers (2)

KyleMit
KyleMit

Reputation: 29829

Starting with aspnet core 2.1, dotnet added the ProblemDetails class as a standardized way for APIs to report errors, based on the RFC 7807.
Starting with aspnet core 7.0, the preferred way to return problem detail objects from your controller actions is via TypedResults.Problem.

In your action just return the following:

return TypedResults.Problem("Hey", statusCode: StatusCodes.Status422UnprocessableEntity);

TypedResults.Problem

Note that the content type is application/problem+json in the response header. You can use this to detect and then consistently deserialize error details which will always have a type, title, status, and detail property (per the spec) as well as extra fields the api might have sent back for extra info.

Previous Alternatives

By comparison, here are other methods to return just a status code OR a status code and a plain text response body

TypedResults.StatusCode

TypedResults.UnprocessableEntity

Note that when we just return TypedResults.StatusCode that the body is empty. When using the TypedResults.UnprocessableEntity helper method, you get a status code and can add a detail to the body, but it's just plaintext and doesn't offer much in the way of standardization and extensibility.

Further Reading

Upvotes: 3

DavidG
DavidG

Reputation: 118937

Yes, you can use the Results class in minimal APIs. Here's an example.

Map the endpoint:

app.MapGet("getsomething", MyHandlerMethod);

And the actual method:

public IResult MyHandlerMethod() 
{
    var result = ...;

    return result.StatusCode == (int) HttpStatusCode.Created
        ? Results.StatusCode(result.StatusCode)
        : Results.Problem("Problem!) ;
}

Upvotes: 2

Related Questions