How to add Pre and Post Processing Logic in ASP.NET Core MVC or WebApi

Every application requires does some kind of Pre and Post-processing logic to sometimes validate or to do custom logic before executing and returning the actual result. ASP.NET Core provides multiple ways to do the same namely Filters, Middlewares, etc...

We can have multiple middlewares, Filters in a typical application to validate or to do custom implementation to every request in the web application.

A filter is one of the ways to validate your session every time a request comes to your application.

There are different kinds of Filter in ASP.Net Core

  1. Authorization Filter
  2. Action Filter
  3. Result Filter
  4. Exception Filter
In this post, we are going to discuss ActionFilter in which we will validate Session before hitting Controller method/endpoint.

Step 1: Create a filter named say "SessionValidatorFilter" which will inherit IAsyncActionFilter and implement the OnActionExecutionAsync method which will validate the session before actually executing Controller Action/Method.

public class SessionValidatorFilter : IAsyncActionFilter
{
private readonly IHttpContextAccessor _httpContextAccessor;
public SessionValidatorFilter(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}

public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
// Do something before the action executes.

string token = context.HttpContext.Request.Headers["token"];
if (token == null)
{
context.HttpContext.Response.StatusCode = 400; // BadRequest
await context.HttpContext.Response.WriteAsync("Token Missing");
return;
}
else if(token != _httpContextAccessor.HttpContext.Session.GetString("token"))
{
context.HttpContext.Response.StatusCode = 401; //UnAuthorized
await context.HttpContext.Response.WriteAsync("UnAuthorized");
return;
}

// next() calls the action method.
var resultContext = await next();
// resultContext.Result is set.
// Do something after the action executes.
}
}


Step 2: Register the filter in ConfiguresServices method in Startup.cs file like below

services.AddScoped<SessionValidatorFilter>();


Step 3: Decorate the Filter as an Attribute in the Controller or specific Controller method

[ServiceFilter(typeof(SessionValidatorFilter))]
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase


If you want to use for all the controllers methods in your application then you register the filter in ConfigureServices method like below and skip Step 3 

services.AddMvc(options =>
{
options.Filters.Add(typeof(SessionValidatorFilter));
})


Hope you have enjoyed the article.

Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee