Skip to content

Instantly share code, notes, and snippets.

@xiaomi7732
Last active October 10, 2023 21:29
Show Gist options
  • Save xiaomi7732/22ef66de6dacc2f3ba724acbf35443de to your computer and use it in GitHub Desktop.
Save xiaomi7732/22ef66de6dacc2f3ba724acbf35443de to your computer and use it in GitHub Desktop.
How to Create ASP.NET Core Filter with Parameters

Accept the parameter on the attribute

using Microsoft.AspNetCore.Mvc;

namespace FiltersDemo;

public class ExampleFilterAttribute : TypeFilterAttribute
{
    public ExampleFilterAttribute(AnEnum enumValue) : base(typeof(ExampleFilter))
    {
        // ...
        // Put the arguments into an object list like this:
        Arguments = new object[] { enumValue };
    }
}

Update the constructor on the Filter to accept the arguments

using System;
...

namespace FiltersDemo;

public class ExampleFilter : IAsyncAuthorizationFilter
{
    private readonly ILogger _logger;

    private readonly AnEnum _enumValue;

    public ExampleFilter(
        AnEnum enumValue,
        ILogger<ExampleFilter> logger
        )
    {
        _logger = logger ?? throw new ArgumentNullException(nameof(logger)); // ILogger<T> would be coming down from DI container
        _enumValue = enumValue;   // enumValue comes down from the Arguments of the attribute above.
    }

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        ...
    }
}

Apply the attribute with the argument

using System;
...

namespace FiltersDemo;

// Apply the filter, with an argumnet of EnumValue.Query.
[ExampleFilter(EnumValue.Query)]
public class MyController : ControllerBase
{
    ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment