3

I want to apply a filter to all asp.net core minimal API endpoints.

The reason I want to do this is to post-process the return values of the endpoint. Something like this:

    public class GlobalFilter : IEndpointFilter
    {
        private ILogger _logger;

        public GlobalValidationFilter(ILogger<GlobalValidationFilter> logger)
        {
            _logger = logger;
        }

        public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext invocationContext, EndpointFilterDelegate next)
        {
            try
            {
                var res = await next(invocationContext);
                var result = res as Result;
                if(result is not null)
                {
                    // Here, access the `result` members and modify the return value accordingly...
                }

                return Results.Problem();
            }
            catch (Exception ex)
            {
                return Results.Problem(ex.ToString());
            }
        }
    }
            app
                .MapPost("api/document/getById", async ([FromBody] GetDocumentRequest request) =>
                {
                    var result = ...result-producing call...;
                    return result;
                })
                .AddEndpointFilter<GlobalFilter>() // Manually assigning the filter.
                ...
                ...;

This appears to work, but I would have to remember to set the filter manually every time. Is there a way to apply this filter to all endpoints automatically?

Alternatively, is it possible to achieve the same thing with another method? From what I have seen, using a middleware does not allow you to inspect the endpoint return values, but only handle thrown exceptions.

2
  • 2
    Maybe middleware is a better option for you? If not this article has a suggestion on how you might apply global filters. Commented Apr 19, 2024 at 10:12
  • @Peppermintology From what I have seen, a middleware doesn't allow inspecting the endpoint return values. The link seems interesting though. Commented Apr 19, 2024 at 10:23

1 Answer 1

2

You can apply the filter to a MapGroup, the MapGroup can point to all your minimal endpoints.

Example:

public static class GroupEndPointsExt
{
    public static RouteGroupBuilder MapMinimalApi(this RouteGroupBuilder group)
    {
      group.MapPost("document/getById", async ([FromBody] GetDocumentRequest request) =>
      {
                    var result = ...result-producing call...;
                    return result;
       });
//add other minimal endpoints here where global filter will apply
        return group;
    }
}

Then in your Program.cs apply the GlobalFilter to the route group that encompasses all your minimal endpoints defined in method MapMinimalApi

app.MapGroup("api").MapMinimalApi().AddEndpointFilter<GlobalFilter>();
//Global filter will apply to all endpoints in this route group
//all endpoints in this route group will use path prefixed with api
Sign up to request clarification or add additional context in comments.

2 Comments

This could help a lot, although it might move the problem to the group-level, instead of the endpoint-level. Right now, I don't use groups at all, so it might be a viable solution for my case.
@user2173353 Route-Groups are just a way to organize groups of endpoints with a common prefix and also will help you enforce DRY.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.