5

I am having an action and attribute as following, i have over-ridden OnActionExecuting and want to read attribute in that method

[MyAttribute(integer)]
public ActionResult MyAction()
{
}


protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    //here i want to read integer passed to action using Attribute
}

1 Answer 1

10

Try it:

Controller

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
  foreach (var filter in filterContext.ActionDescriptor.GetCustomAttributes(typeof (MyAttribute), false).Cast<MyAttribute>())
  {
    var desiredValue = filter.Parameter;
  }

  base.OnActionExecuting(filterContext);
}

Filter

public class MyAttribute : FilterAttribute, IActionFilter
{
  private readonly int _parameter;

  public MyAttribute(int parameter)
  {
    _parameter = parameter;
  }

  public int Parameter { get { return _parameter; } }

  public void OnActionExecuted(ActionExecutedContext filterContext)
  {
    //throw new NotImplementedException();
  }

  public void OnActionExecuting(ActionExecutingContext filterContext)
  {
    //throw new NotImplementedException();
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

For a complete explanation of Action Filters, check out this article: learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/…

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.