I am working on a minimal API and I am trying to make an actionfilter for authentication works with it.
I tried to add my action filter directly on the endpoint registration likeso:
app.MapGet("/Users/{userId}", [ServiceFilter(typeof(CustomAuthorizationAttribute))] async (IMediator mediator, string userId) =>
{
//SomeCode
});
I also tried with the attribute directly.
app.MapGet("/Users/{userId}", [CustomAuthorizationAttribute()] async (IMediator mediator, string userId) =>
{
//SomeCode
});
At first I tried to make an extension to add it in a more elegant way and it didn't work either.
public static TBuilder AddCustomAuthorizationAttribute<TBuilder>(this TBuilder builder) where TBuilder : IEndpointConventionBuilder
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Add(endpointBuilder =>
{
endpointBuilder.Metadata.Add(new CustomAuthorizationAttribute());
});
return builder;
}
There is my simple ActionFilter. I am placing my breakpoint under the onActionExecuting code to intercept when the attribute get called but it never get called.
public class CustomAuthorizationAttribute : ActionFilterAttribute, IAsyncActionFilter
{
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context); //BreakPoint
}
public override Task OnActionExecutionAsync(ActionExecutingContext context,ActionExecutionDelegate actionExecutionDelegate)
{
return base.OnActionExecutionAsync(context, actionExecutionDelegate); //BreakPoint
}
}
Action filters are part of ASP.NET Core MVC pipeline and are not applicable (at least at the moment of writing) to Minimal APIs.
UPD
Starting .NET 7 Minimal API's will have similar feature allowing to use AddFilter
method. See also issue1 issue2, PR, and IRouteHandlerFilter
interface.