Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing action method parameter to ActionFilterAttribute in asp.net mvc

I know that I can use the filterContext to get to it. However, this is not very flexible if the action method parameter is named differently. This should work:

[HttpGet] [NewAuthoriseAttribute(SomeId = id)] public ActionResult Index(int id) {     ...  public class NewActionFilterAttribute : ActionFilterAttribute {        public int SomeId { get; set; }     ... 

but it does not (it does not even compile). Any ideas?

like image 702
cs0815 Avatar asked Mar 20 '13 17:03

cs0815


1 Answers

Building on the answer from @Pankaj and comments from @csetzkorn:

You pass the name of the parameter as a string then check the filterContext

public class NewAuthoriseAttribute : ActionFilterAttribute {     public string IdParamName { get; set; }      public override void OnActionExecuting(ActionExecutingContext filterContext)     {         if (filterContext.ActionParameters.ContainsKey(IdParamName))         {             var id = filterContext.ActionParameters[IdParamName] as Int32?;         }     } }  [NewAuthorizeAttribute(IdParamName = "fooId")] public ActionResult Index(int fooId) { ... } 
like image 156
Jasen Avatar answered Sep 20 '22 09:09

Jasen