Skip to content

Add support for filter factory to minimal APIs #40513

Closed
@captainsafia

Description

@captainsafia

Background and Motivation

To support providing users with the ability to generate endpoint filters that target route handlers based on their method signature, we are adding support for a new "filter factory" API that allows users to access the MethodInfo associated with a route handler when constructing their filter.

Proposed API

Introduce new RouteHandlerFilterDelegate type and replace instances of Func<RouteHandlerFilterContext, ValueTask<object?> with it.

+ namespace Microsoft.AspNetCore.Http;

+ public delegate ValueTask<object?> RouteHandlerFilterDelegate(RouteHandlerFilterContext context);
public interface IRouteHandlerFilter
{
- ValueTask<object?> InvokeAsync(RouteHandlerFilterContext context, Func<RouteHandlerFilterContext, ValueTask<object?>> next);
+ ValueTask<object?> InvokeAsync(RouteHandlerFilterContext context, RouteHandlerFilterDelegate next)
}

Instead of taking a list of IRouteHandlerFilters directly, the RequestDelegateFactory now takes in a list of delegates representing the factory in the generation.

public sealed class RequestDelegateFactoryOptions
{
-   public IReadOnlyList<IRouteHandlerFilter>? RouteHandlerFilters { get; init; }
+   public IReadOnlyList<Func<MethodInfo, RouteHandlerFilterDelegate, RouteHandlerFilterDelegate>>? RouteHandlerFilterFactories { get; init; }
}

And finally, we add a new extension method to that takes the filter factory delegates directly.

namespace Microsoft.AspNetCore.Builder;

public static class RouteHandlerFilterExtensions
{
+   public static RouteHandlerBuilder AddFilter(this RouteHandlerBuilder builder, Func<MethodInfo, RouteHandlerFilterDelegate, RouteHandlerFilterDelegate> filterFactory);
}

Usage Examples

app.MapGet("/foo/{id}", (int id) => ...)
  .AddFilter(
    (methodInfo, next) =>
      {
          var doubleTrouble = methodInfo.GetParameters().Length == 2;
          return async (context) => {
            if (doubleTrouble) ..
           }
      }));

Metadata

Metadata

Assignees

Labels

Priority:1Work that is critical for the release, but we could probably ship withoutapi-approvedAPI was approved in API review, it can be implementedarea-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etcfeature-minimal-actionsController-like actions for endpoint routingold-area-web-frameworks-do-not-use*DEPRECATED* This label is deprecated in favor of the area-mvc and area-minimal labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions