在 asp.net mvc3 中的 OnAction 执行中读取属性

5

我有以下的一个操作和属性,我已经重写了 OnActionExecuting 方法,并希望在该方法中读取属性。

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


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

10

试一试:

控制器

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

有关 Action Filters 的完整解释,请参阅此文章:https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs - Tod Birdsall

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接