Description
In the MVC lifecycle, the Action Filter executes before invoking the action. These filters are provided with the action context from which we can access and manipulate the controller context.
In this example, I will show how to access a service in an action filter, and add data in the ViewData that can be used on the View.cshtml page
Code
public class MyActionFilter : Attribute, IActionFilter { public void OnActionExecuted(ActionExecutedContext context) { } public void OnActionExecuting(ActionExecutingContext context) { Controller controller = context.Controller as Controller; if (controller != null) { //getting a service IMyService myService = controller.HttpContext.RequestServices.GetService(typeof(IMyService)) as IMyService; //injecting values in the ViewData controller.ViewData["myservice"] = myService; } } }
Add the action filter in the controller’s action
public class MyController : Controller { [MyActionFilter] public Task Login() { //logic return View();//ViewData will have our object } }