2011-08-20 19 views
5

Tôi gặp một hành động và thuộc tính như sau, tôi đã trên một thanh cuộn OnActionExecuting và muốn đọc thuộc tính trong phương pháp màĐọc thuộc tính trong OnAction Thi trong asp.net MVC3

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


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

Trả lời

10

Thử:

khiển

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

Lọc

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

Để có giải thích đầy đủ về Bộ lọc hành động, hãy xem bài viết sau: https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/hiểu-hành động-bộ lọc-cs –

Các vấn đề liên quan