Result Filter in ASP.NET CORE MVC

If you want to execute logic before or after generating result then use Result filter. This filter can be applied to the controller or action method.

Result filter

  • IResultFilter
    • OnResultExecuting
    • OnResultExecuted
  • IAsyncResultFilter
    • OnResultExecutionAsync

We have 2 types of Result filter one is Sync and another is Async, for implementing Sync type we need to inherit IResultFilter and for implementing Async type we need to inherit IAsyncResultFilter.

IResultFilter has 2 methods in it OnResultExecuting, OnResultExecuted the OnResultExecuting method is called first before the result is returned here you make a change in the request.

The asynchronous version of the result filter to use Result filters, we need to implement the IAsyncResultFilter interface. IAsyncResultFilter has 1 method in it OnResultExecutionAsync.

Result filters are only executed for successful results.

To Create Sync Result filters, we need to implement the IResultFilter interface.

Implementation

using Microsoft.AspNetCore.Mvc.Filters;
using System;

namespace WebApplication4.Filters
{
    public class CustomResultFilterAttribute : Attribute, IResultFilter
    {
        public void OnResultExecuted(ResultExecutedContext context)
        {
        }
        public void OnResultExecuting(ResultExecutingContext context)
        {
        }
    }
}

Let’s create a Custom ResultFilter with name CustomResultFilterAttribute and we are going to inherit it with Attribute class and IResultFilter interface and implement OnResultExecuted and OnResultExecuting method and in OnResultExecuting method, we are going to add headers to a page with the name MyPageHeader.

Code Snippet of CustomResultFilterAttribute

using Microsoft.AspNetCore.Mvc.Filters;
using System;

namespace WebApplication4.Filters
{
    public class CustomResultFilterAttribute : Attribute, IResultFilter
    {
        public void OnResultExecuted(ResultExecutedContext context)
        {
            if (context.Exception == null)
            {

            }
        }

        public void OnResultExecuting(ResultExecutingContext context)
        {
            var headerName = "MyPageHeader";
            context.HttpContext.Response.Headers.Add(headerName, new string[] { "MyPageHeader" });

        }
    }
}

How to Apply Filter on Controller

using System;
using Microsoft.AspNetCore.Mvc;
using WebApplication4.Filters;

namespace WebApplication4.Controllers
{
    [TypeFilter(typeof(CustomResourceFilter))]
    public class DefaultController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

View after adding the header

IAsyncResultFilter

The asynchronous version of the result filter to use Result filters, we need to implement the IAsyncResultFilter interface.

IAsyncResultFilter has 1 method in it OnResultExecutionAsync in this method we are going to add a header. After adding a header, we are going to execute the action method and see if we have any exception in it if yes then we have set ResultExecutedContext.Cancelled to true then action result execution was short-circuited by another filter.

Implementation

using Microsoft.AspNetCore.Mvc.Filters;
using System.Threading.Tasks;

namespace WebApplication4.Filters
{
    public class CustomAsyncResultFilterAttribute : IAsyncResultFilter
    {
        public Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            throw new System.NotImplementedException();
        }
    }
}

Code Snippet of CustomAsyncResultFilterAttribute

using Microsoft.AspNetCore.Mvc.Filters;
using System.Threading.Tasks;

namespace WebApplication4.Filters
{
    public class CustomAsyncResultFilterAttribute : IAsyncResultFilter
    {
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            var headerName = "MyPageHeader";
            context.HttpContext.Response.Headers.Add(headerName, new string[] { "MyPageHeader" });
            ResultExecutedContext resultContext = await next();

            if (resultContext.Exception != null)
            {
                resultContext.ExceptionHandled = true;
                resultContext.Canceled = true;
            }
        }
    }
}

How to Apply Filter on Controller

using System;
using Microsoft.AspNetCore.Mvc;
using WebApplication4.Filters;

namespace WebApplication4.Controllers
{
    [TypeFilter(typeof(CustomAsyncResultFilterAttribute))]
    public class DefaultController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

By Saineshwar Bageri

I am Microsoft MVP | C# Corner MVP | Code Project MVP | FULL STACK .NET Developer and working on .Net Web Technology (Asp.net, Asp.net Core,.Net Core, C#, Sqlserver, MVC, Windows, Console Application, javascript, jquery, json, ORM Dapper) and also a freelance developer.