Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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.

>Solution :

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.).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading