我有一个 Action 和属性,如下所示,我已覆盖OnActionExecuting并想在该方法中读取属性

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


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

最佳答案

尝试一下:

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);
}

过滤
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();
  }
}

关于c# - 在ASP.NET MVC3中的OnAction执行中读取属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7134297/

10-10 13:04