asp.net-mvc-2action-filterdynamic-variablescustom-action-filter

How to pass dynamic variable to Action Filter in ASP.NET MVC


I would like to use a variable to pass a dynamic value to my action filter. I thought it would be something like this:

[MessageActionFilter(message = "User is updating item: " & id)]
public ActionResult doSomething(int id)
{
    // do something
}

However, it seems that the parameter must be a constant value. Therefore, my question is how do I get the variable to my action filter?


Solution

  • You can get the parameter values in OnActionExecuting using the ActionExecutingContext.ActionParameters property.

    It's just a pseudo code, but for example you can retrive the parameter named id

    public class MessageActionFilter: ActionFilterAttribute 
    {     
        public override void OnActionExecuting(ActionExecutingContext filterContext)     
        {         
            var response = filterContext.HttpContext.Response;                   
    
            var parameterValue = filterContext.ActionParameters.SingleOrDefault(p => p.Key == "id");
    
            // check if not null before writing a message
    
            response.Write(this.Message + parameterValue); // prints "User is updating item: <idvalue>"
        }
    
        public string Message {get; set;}
    } 
    

    Tell me if it helps.