0

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(
  {
  }

1 Answer 1

1

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()
{
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.