Contact

MVC Filters


In MVC Dot net, every request for MVC is  routed through route table and it searches for requested controller and action for response. But for certain circumstances where  developer wants to execute certain logic before execution of request controller and action. Filters allows you to inject some logic in request pipeline.

Below are the filters provided by ASP.NET MVC. These are executed in given order also
  • Authentication Filter - Introduced in MVC 5
  • Authorization Filter
  • Action Filter 
  • Result Filter
  • Exception Filter
 you can register above filters on different places as per the suitable for the requirement

  • Global Level
  • Controller Level
  • Action Level

I will try to describe each of the filter as per my experience and acceptable way.

1) Authentication Filter

In MVC 4, developer were using Authorization Attribute to execute some authentication task for the current request. It was very convenient because Authorization filter  executes before any other filters.
This is introduced in MVC 5, this filter runs before any other filter and action runs. This filter ensures a valid user is using the application. This filter implements IAuthenticationFilter interface. 
[NOTE] - To be able to use these filters as your standard Action Filters on action/controller as attribute you should also implement from ActionFilterAttribute.

IAuthenticationFilter implements two method 
  • OnAuthentication
  • OnAuthenticationChallenge
OnAuthentication- this method get executed first. It performs the execution to check the authentication. during Action invocation MVC
                    invokes OnAuthentication method by following code

AuthenticationContext authenticationContext = InvokeAuthenticationFilters(controllerContext, filterInfo.AuthenticationFilters, actionDescriptor);

This method creates an AuthenticationContext using the original principal, and executes each filter's OnAuthentication method. 

OnAuthenticationChallenge - The is used to restrict access based upon the authenticated user's principal. It is used to perform some additional task on the request.

   public class WetwareAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter    {
        public void OnAuthentication(AuthenticationContext filterContext)
{           
if (filterContext.HttpContext.User.Identity.IsAuthenticated &&
(filterContext.HttpContext.User.IsInRole(superAdminRole)
|| filterContext.HttpContext.User.IsInRole(adminRole)))
{
// do nothing
}
            //Or We can also write as below
            //Check Session is Empty Then set as Result is HttpUnauthorizedResult
else if (string.IsNullOrEmpty(Convert.ToString(filterContext.HttpContext.Session["UserID"])))
{
filterContext.Result = new HttpUnauthorizedResult();
            } else
{
filterContext.Result = new HttpUnauthorizedResult(); // mark unauthorized
}
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
            //Here we can check Result is null or Result is HttpUnauthorizedResult , if yes then we are Redirect to Error View
if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result = new RedirectToRouteResult("Default",
new System.Web.Routing.RouteValueDictionary{
{"controller", "Account"},
{"returnUrl", context.HttpContext.Request.RawUrl}
{"action", "Login"}, }); }
}
    }
To apply this WetwareAuthenticationAttribute, find below code
  public class HomeController : Controller {
public ActionResult Index()
{
Session["UserID"] = "Any Session Value to identify user is logged in";
return View();
}
[WetwareAuthentication]
    public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
}

For some special requirement, It can also be used to authenticate user and provide different identity for some specific controller, such as different authentication provider. 

2) Authorization Filter

Authorization filter confirms that you are permissible to manipulate the section or not.

public class WetwareAuthorizeAtrribute : IAuthorizationFilter
    {
        string[] rolesApplied;
        public WetwareAuthorizeAtrribute(params string[] _userRoles)
        {
            this.rolesApplied = _userRoles;
        }
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            bool authorized = false;
            var currentUser = filterContext.RequestContext.HttpContext.User;

            //or GetUser from database with roles passed and current login user to filter
            if (currentUser == null)
            {
                throw new UnauthorizedAccessException(currentUser.Identity.Name + " is not authorized!");
            }
            foreach (string role in rolesApplied)
            {
                if (!currentUser.IsInRole(role))
                    authorized = false;
            }
            if(!authorized)
            {
                throw new UnauthorizedAccessException(currentUser.Identity.Name +" is not authorized!");
            }
        }
    }
To apply this WetwareAuthorizeAttribute, find below code
  public class HomeController : Controller {
        [WetwareAuthorize("SuperAdmin","Admin")]
public ActionResult UserList()
{
ViewBag.Message = "Your application description page.";
return View();
}
    }

3) Action Filter
There may be some requirement(Logging/) to execute some piece of code before and after of requested controller/action execution .  In this scenario Action Filter comes into picture.
It can be applied on action or on Controller(execute for each defined action) 

OutputCache is a builtin action filter

Developer can create his own Actionfilter based upon the scenarios.
To create custom ActionFilter you need to inherit/implement IFilterAttribute interface.

It has two member which need to implement
    OnActionExecuted(ActionExecutedContext filterContext)
    OnActionExecuting(ActionExecutingContext filterContext)

The Base ActionFilterAttribute Abstract Class

You can also user ActionFilterAttribute class to easily create ActionFilters. This class contains members for IActionFilter and IResultFilter.

The base ActionFilterAttribute class has the following methods that you can override:

OnActionExecuting - This method is called before a controller action is executed.
OnActionExecuted - This method is called after a controller action is executed.
OnResultExecuting - This method is called before a controller action result is executed.
OnResultExecuted - This method is called after a controller action result is executed.

Share us on

Get In Touch