2

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?

Jason
  • 17,276
  • 23
  • 73
  • 114

1 Answers1

3

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.

TheAtomicOption
  • 1,456
  • 1
  • 12
  • 21
Tomasz Jaskuλa
  • 15,723
  • 5
  • 46
  • 73