In this recipe, you will learn how to use a filter globally, and understand the difference between using a filter globally and using middleware.
- First, let's create a
ResultFilter
class by deriving fromIResultFilter
:
public class MyResultFilter : IResultFilter { public void OnResultExecuting(ActionExecutingContext context) { // do something before the action executes } public void OnResultExecuted(ActionExecutedContext context) { // do something after the action executes ViewResult result = context.Result as ViewResult; if (result != null) { result.ViewData["globalMessage"] = "Comes from MyActionAttributeFilter at " + DateTime.Now.ToLongTimeString(); } } }
- Next, let's configure this filter to be used as a global filter in
Startup.cs
. We can do this in two ways; by type, or by instance:
services.AddMVC(config =...