Search code examples
asp.net-mvcasp.net-mvc-3asp.net-mvc-4

How do I pass variables to a custom ActionFilter in ASP.NET MVC app


I have a controller in my MVC app for which I'm trying to log details using a custom ActionFilterAttribute, by using the onResultExecuted method.

I read this tutorial to understand and write my own action filter. The question is how do I pass variables from the controller to the action filter?

  1. I want to get the input variables with which a controller is called. Say, the username/user ID.
  2. If (in some situations) an exception is thrown by any controller method, I would want to log the error too.

The controller -

[MyActionFilter]
public class myController : ApiController {
    public string Get(string x, int y) { .. }
    public string somemethod { .. }
}

The action filter -

public class MyActionFilterAttribute : ActionFilterAttribute {
    public override void onActionExecuted(HttpActionExecutedContext actionExecutedContext) {
        // HOW DO I ACCESS THE VARIABLES OF THE CONTROLLER HERE
        // I NEED TO LOG THE EXCEPTIONS AND THE PARAMETERS PASSED TO THE CONTROLLER METHOD
    }
}

I hope I have explained the problem here. Apologies if I'm missing out some basic objects here, I'm totally new to this.


Solution

  • Approach - 1

    Action Filter

    public class MyActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
        }
    }
    

    Action Method

    [MyActionFilter]
    public ActionResult Index()
    {
        ViewBag.ControllerVariable = "12";
        return View();
    }
    

    enter image description here

    If you pay attention to the screenshot, you can see the ViewBag information

    Approach - 2

    Action Filter

    public class MyActionFilter : ActionFilterAttribute
    {
        //Your Properties in Action Filter
        public string Property1 { get; set; }
        public string Property2 { get; set; }
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
        }
    }
    

    Action Method

    [MyActionFilter(Property1 = "Value1", Property2 = "Value2")]
    public ActionResult Index()
    {
        return View();
    }