Home > Mobile >  Using IResult as return value for "classic" api instead of Minimal API
Using IResult as return value for "classic" api instead of Minimal API

Time:12-08

I have multiple services that return IResult and don´t want to use minimal API structure, but I want to use the same return type IResult, but when I use that in the controller it always returns Ok:

Minimal API example that returns 400 Bad request:

app.MapPut("test", async () =>
{
    return Results.BadRequest("hello");
});

The classic controller that returns 200 Ok:

[ApiController]
public class TestController : ControllerBase

    [HttpPut("test")]
    public async Task<IResult> Test()
    {
        return Results.BadRequest();
    }

Is there an easy way to fix this or do I need a mapping function?

I am using .net 6.

CodePudding user response:

Technically you can call IResult.ExecuteAsync on the ControllerBase's context:

public class SomeController : ControllerBase
{
    public async Task SomeAction()
    {
        IResult result = Results.BadRequest(); // dummy result, use one from the service
        await result.ExecuteAsync(HttpContext);
    }
}

But in general it is better to follow standard patterns and in this case make your service return some custom app-specific response which is "platform-agnostic" i.e. it should not depend on web framework used and represent some business/domain related entity/data. Potentially you can look into some library which can represent "result" abstraction. For example FluentResults or go a bit more functional with some kind of Either (many options here CSharpFunctionalExtensions, language-ext, Optional, etc.).

CodePudding user response:

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [HttpPut]
    public IActionResult Test()
    {
        return BadRequest("...from Test...");
    }
}

The URL to hit it is /test

  • Related