user911
user911

Reputation: 1559

Unable to get custom attributes in asp.net action filter

I have created a custom attribute and I am trying to retrieve the value of this custom attribute in asp.net action filter but it seems to be unavailable. What am I doing wrong?

 [AttributeUsage(AttributeTargets.Method, Inherited = true)]
 public sealed class MyCustomAttribute : Attribute
 {
   MyCustomAttribute(string param)
   {
   }
 }

 public class MyCustomActionFilter : IActionFilter
 {
   public void OnActionExecuted(ActionExecutedContext context)
   {
    throw new NotImplementedException();
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
     // unable to find my custom attribute here under context.Filters or anywhere else.
     }
  }   

  [HttpGet]
  [MyCustomAttribute ("test123")]
  public async Task<Details> GetDetails(
  {
  }

Upvotes: 0

Views: 577

Answers (1)

mwilczynski
mwilczynski

Reputation: 3082

What you want to achieve is a little more complicated if you want to do it yourself (ie. reflecting attribute value from method of Controller). I would recommend using built-in attribute filters from ASP.NET Core (more in ASP.NET Core documentation), in your example:

public class MyCustomActionAttribute : ActionFilterAttribute
{
    private readonly string param;

    public MyCustomActionAttribute(string param)
    {
        this.param = param;
    }

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var paramValue = param;
        base.OnActionExecuting(context);
    }
}

and annotating your controller action like this:

[HttpGet]
[MyCustomAction("test123")]
public async Task<Details> GetDetails()
{
}

Upvotes: 1

Related Questions