Can one get parameter values used in a method from within an ActionFilter?

alphadogg picture alphadogg · Dec 23, 2010 · Viewed 14.3k times · Source

Assume I have a controller method like this:

[Audit]
public JsonNetResult List(int start, int limit, string sort, string dir, string searchValue, SecurityInputModel securityData)
{
    ...
}

and an attribute defined as such:

[AttributeUsage(AttributeTargets.Method)]
public class AuditAttribute : ActionFilterAttribute
{

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // auditing code here

        base.OnActionExecuted(filterContext);

    } 
}

can I get at the value of start/limit/sort/etc from inside OnActionExecuted()?

Answer

Jeff Ogata picture Jeff Ogata · Dec 23, 2010

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

For example, the following test attribute writes the parameter names and values out to the response (the ItemModel class overrides ToString to just output its 2 properties):

public class CustomActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var response = filterContext.HttpContext.Response;

        response.Write(filterContext.ActionDescriptor.ActionName);
        response.Write("<br/>");

        foreach (var parameter in filterContext.ActionParameters)
        {
            response.Write(string.Format("{0}: {1}", parameter.Key, parameter.Value));
        }
    }
}

[CustomActionFilter]
[HttpPost]
public ViewResult Test(ItemModel model)
{
    return View(model);
}

alt text