Moddaman
Moddaman

Reputation: 2778

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:

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

Upvotes: 2

Views: 2521

Answers (2)

davidfowl
davidfowl

Reputation: 38764

This is supported in .NET 7 now.

using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();

app.Run();

public class Home : ControllerBase
{
    [HttpGet("/")]
    public IResult Get() => Results.Ok("Okies");
}

Upvotes: 2

Guru Stron
Guru Stron

Reputation: 141565

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

Upvotes: 3

Related Questions