Home > Net >  C# .NET - Access to an instance of attribute filter
C# .NET - Access to an instance of attribute filter

Time:01-03

I have following filter:

public class UserAuthFilter : ActionFilterAttribute, IActionFilter
{
   public bool AllowAnonymous { get; set; } = false;
   public string Name { get; set; };
   
   public UserAuthFilter(bool allowAnonymous = false, string name = "") 
   {
      this.AllowAnonymous = allowAnonymous;
      this.Name = name;
   }
 
   public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
   {
        // some actions
        await next();
   }

}

and I apply this filter on a controller's method like this:

[HttpPost]
[UserAuthFilter]
public async Task<IActionResult> Create(CreateDataRequest request)
{
    //
    // here I would like to have an instance of the applying UserAuthFilter
    //
    return service.Create(request);
}

Is it possible to obtain the instance of the applied filter on the commented place?

Thank you very much

I tried to set the attributes as static variables and than access these attributes staticaly like UserAuthFilter.AllowAnonymous, but this approach not seems to be okay.

CodePudding user response:

Sure, you can modify the items/properties bag of the HTTP request, as such:

public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
  // some actions
  context.HttpContext.Items["UserAuthFilter"] = this;
  await next();
}

accessed as such:

[HttpPost]
[UserAuthFilter]
public async Task<IActionResult> Create(CreateDataRequest request)
{
  var filter = HttpContext.Items["UserAuthFilter"] as UserAuthFilter;
  return service.Create(request);
}
  • Related