Search code examples
c#minimal-apis

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?


Solution

  • 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!) ;
    }