How to use Result filters in ASP.NET Core MVC?
Result filter can run code immediately before and after the execution of individual action results. They run only when the action method has executed successfully. They are useful for logic that must surround view or format execution.
As the diagram shows the order of execution in the MVC execution pipeline,
Implement either the IResultFilter or IAsyncResultFilter interface. Their execution surrounds the execution of action results.
A difference between IResultFilter & IActionFilter will provide a more clear idea to understand IResultFilter.
A Result filters IResultFilters contain logic which is executed before and after a view result is executed. Sometimes we might want to modify a view result just before the view is rendered. Whereas Action filters contain logic that is executed before and after a controller action executes. We can use an action filter, for instance, to modify the view data that a controller action returns.
In order to implement the Result filter in MVC, Fist we need to create a custom filter attribute class and implement the IResultFilter interface. interface provides us two methods OnResultExecuting and OnResultExecuted similar to other filters.
Example of a Result filter which implements IResultFilter, that adds an HTTP header is shown below,
public class AddHeaderFilterWithDi : IResultFilter
{
private ILogger _logger;
public AddHeaderFilterWithDi
(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.
CreateLogger<AddHeaderFilterWithDi>();
}
public void OnResultExecuting
(ResultExecutingContext context)
{
var headerName = "OnResultExecuting";
context.HttpContext.Response.
Headers.Add(
headerName, new string[]
{ "ResultExecutingSuccessfully" });
_logger.LogInformation
($"Header added: {headerName}");
}
public void OnResultExecuted
(ResultExecutedContext context)
{
// Can't add to headers here because the response has already begun.
}
}
The OnResultExecuting method can short-circuit execution of the action result and subsequent result filters by setting ResultExecutingContext.Cancel to true. You should generally write to the response object when short-circuiting to avoid generating an empty response.
Throwing an exception will,
- Prevent execution of the action result and subsequent filters.
- Be treated as a failure instead of a successful result.
So as we had seen in all filters of ASP.NET MVC Core Authorization filters, Resource filters, Action filters, Exception filters and Result filters. If we have to run code before or after certain stages in the request processing pipeline then it's a good idea to ASP.NET Core filters.