MrDave1999 / SimpleResults

A simple library to implement the Result pattern for returning from services
https://mrdave1999.github.io/SimpleResults
MIT License
103 stars 2 forks source link

Add an endpoint filter to translate the Result object to IResult #49

Closed MrDave1999 closed 9 months ago

MrDave1999 commented 9 months ago

The filter only converts the Result object to an implementation of Microsoft.AspNetCore.Http.IResult.

Example

public static class PersonEndpoint
{
    public static void AddRoutes(this WebApplication app)
    {
        var personGroup = app
            .MapGroup("/Person")
            .WithTags("Person")
            .AddEndpointFilter<TranslateResultToHttpResultFilter>();

        personGroup
            .MapPost("/", ([FromBody]Person person, PersonService service) => service.Create(person))
            .Produces<Result>();

        personGroup
            .MapGet("/", (PersonService service) => service.GetAll())
            .Produces<ListedResult<Person>>();
    }
}

TranslateResultToHttpResultFilter must implement the IEndpointFilter interface.

The detail to take into consideration is that IEndpointFilter is only available as of ASP.NET Core 7.0. This means that the custom filter should be compiled for specific frameworks such as .NET 7, 8 or higher.

As the SimpleResults.AspNetCore project has multiple target frameworks, the preprocessor symbols could be used as NET7_0_OR_GREATER. See https://learn.microsoft.com/en-us/dotnet/core/tutorials/libraries#preprocessor-symbols