Description
In the MVC lifecyle ActionFilter execute just before the action is invoked. 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 in the View.cshtml page
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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
1 2 3 4 5 6 7 8 9 10 |
public class MyController : Controller { [MyActionFilter] public Task Login() { //logic return View();//ViewData will have our object } } |
Leave a Comment