Skip to content

Commit

Permalink
Merge pull request #50 from MrDave1999/feat/issue-49
Browse files Browse the repository at this point in the history
* feat: Add an endpoint filter to translate the Result object to Microsoft.AspNetCore.Http.IResult
* docs: Add an example on how to use custom endpoint filter
  • Loading branch information
MrDave1999 committed Dec 10, 2023
2 parents b54c356 + ca5d98b commit a7a3812
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,22 @@ public static class PersonEndpoint
{
public static void AddPersonRoutes(this WebApplication app)
{
var userGroup = app
var personGroup = app
.MapGroup("/Person-MinimalApi")
.WithTags("Person MinimalApi");
.WithTags("Person MinimalApi")
.AddEndpointFilter<TranslateResultToHttpResultFilter>();

userGroup.MapPost("/", async ([FromBody]Person person, PersonService service) =>
personGroup.MapPost("/", async ([FromBody]Person person, PersonService service) =>
{
await Task.Delay(100);
return service
.Create(person)
.ToHttpResult();
return service.Create(person);
})
.Produces<Result>();

userGroup.MapGet("/", async (PersonService service) =>
personGroup.MapGet("/", async (PersonService service) =>
{
await Task.Delay(100);
return service
.GetAll()
.ToHttpResult();
return service.GetAll();
})
.Produces<ListedResult<Person>>();
}
Expand Down
31 changes: 31 additions & 0 deletions src/AspNetCore/TranslateResultToHttpResultFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#if NET7_0_OR_GREATER
using Microsoft.AspNetCore.Http;

namespace SimpleResults;

/// <summary>
/// Translates the Result object to an implementation of <see cref="IResult"/>.
/// <para>Result object can be:</para>
/// <list type="bullet">
/// <item><see cref="Result{T}"/></item>
/// <item><see cref="ListedResult{T}"/></item>
/// <item><see cref="PagedResult{T}"/></item>
/// <item><see cref="Result"/></item>
/// <item>A subtype of <see cref="ResultBase"/>.</item>
/// </list>
/// </summary>
public class TranslateResultToHttpResultFilter : IEndpointFilter
{
/// <summary>
/// Translates the Result object into a corresponding HTTP status code.
/// This translation occurs after an endpoint handler is executed.
/// </summary>
public async ValueTask<object> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
object endpointHandlerResult = await next(context);
return endpointHandlerResult is ResultBase result ?
result.TranslateToHttpResult() :
endpointHandlerResult;
}
}
#endif

0 comments on commit a7a3812

Please sign in to comment.