2011-08-20 17 views
5

Mam działania i jako atrybut po, mam ponad jeździł OnActionExecuting i chcą czytać atrybut w tej metodzieReading atrybut w OnAction Wykonanie w 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 
} 

Odpowiedz

10

Spróbuj:

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

Filtr

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

Aby uzyskać pełne wyjaśnienie działania filtrów, zapoznaj się z tym artykułem: https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs –