Asp MVC Core ActionFilters

visual-studio-asp-net

At this post, I will show some examples of the usages of the action filter of ASP MVC. Action filters enable to process the action before or after it goes in/out of the controller action.

public override void OnActionExecuting(ActionExecutingContext context)
{
	base.OnActionExecuting(context);
	var req = context.HttpContext.Request;
	var access_token = req.Headers["bearer"];

	var currentSession = _SessionRepository.Single(x => x.AccessToken == access_token);
	if (currentSession != null)
	{
		if (access_token == currentSession.AccessToken)
		{
			base.OnActionExecuting(context);
		}
		else
		{
			return;
		}
	}
}

The above code looks for a bearer in the request headers and fetches it. If the bearer token is in the database then it passes the execution to the context, which means normal continuation or else returns void.

The above process might influence you while you are building an authentication system in ASP MVC Core.

The code above is a piece of code under the class, AuthFilter. Now, put the respective filter on the top of the GetNodes action.

[ServiceFilter(typeof(AuthFilter))]
public IActionResult GetNodes(int? Skip, int? Take)     

This way, you will enable the filtration of the request before it goes into other directions.

The code below is taken from https://docs.microsoft.com/tr-tr/aspnet/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-custom-action-filters. This one is another way of using actionfilters but in this case, the actionfilter is defined over the controller class and applied to child actions one by one. These kinds of implementations in real life are useful when you want to log the errors or just simply register the visiting IPs.

public class MyNewCustomActionFilter : ActionFilterAttribute, IActionFilter
{
  void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)

  {
        // TODO: Add your acction filter's tasks here

        // Log Action Filter Call
        MusicStoreEntities storeDB = new MusicStoreEntities();

        ActionLog log = new ActionLog()
        {
             Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
             Action = filterContext.ActionDescriptor.ActionName + " (Logged By: 

MyNewCustomActionFilter)",
             IP = filterContext.HttpContext.Request.UserHostAddress,
             DateTime = filterContext.HttpContext.Timestamp
        };

        storeDB.ActionLogs.Add(log);
        storeDB.SaveChanges();

        this.OnActionExecuting(filterContext);
  }
}