0

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?

Lorena Sfăt
  • 215
  • 2
  • 7
  • 18
  • I don't think there's a built in way but you can probably write such a thing quite easily yourself – Zohar Peled Feb 07 '23 at 11:36
  • 2
    Yes, you can return `Results.StatusCode(...)` and `Results.Problem(...)` – DavidG Feb 07 '23 at 11:37
  • 1
    The methods `Problem()`, `OK()`, `NotFound()` construct the relevant Result objects, eg `OKResult` or `BadRequestObjectResult`. You can construct these objects directly or use the `Results.` convenience methods – Panagiotis Kanavos Feb 07 '23 at 11:51
  • @PanagiotisKanavos Not quite, the `Results` class gives you `IResult` types, these are not the same as the normal MVC `OKResult`/`NotFoundResult` types, and the two things cannot be mixed. – DavidG Feb 07 '23 at 11:55

1 Answers1

2

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!) ;
}
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • Thanks, that's almost wat I was looking for. `return result.StatusCode == (int) HttpStatusCode.Created ? Results.StatusCode(result.StatusCode) : Results.Problem(result.MessageCode, statusCode:result.StatusCode) ;`. I would have liked to have the option for the same parameters for `Results.StatusCode` – Lorena Sfăt Feb 07 '23 at 11:47
  • @LorenaSfăt [Results.Problem](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.results.problem?view=aspnetcore-7.0#microsoft-aspnetcore-http-results-problem(system-string-system-string-system-nullable((system-int32))-system-string-system-string-system-collections-generic-idictionary((system-string-system-object)))) does have the same parameters – Panagiotis Kanavos Feb 07 '23 at 11:56
  • Yes, but I see `Results.StatusCode` doesn't – Lorena Sfăt Feb 07 '23 at 11:57