Friday, August 19, 2016

MVC Filter Order

While dealing with MVC filters we got various options to tweak the flow of action method calls at local and global level of application execution, The best case scenario are as follows:-

1. Check authorization for each action call.
2. Check whether request is legitimate as if it is human or bot based
3. Check or validate model request
4. Check session timeout
5. Check request length

[Authorize]--AuthorizeAttribute


  • IsAuthorized
  • OnAuthorized

public class ProtectedApiAttribute : AuthorizeAttribute
    {
        public ProtectedApiAttribute()
        {
            // do nothing, _repository will be lazily instantiated
        }
 
 
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var methodAccess = string.Empty;
            if (actionContext.Request.Method == HttpMethod.Get) methodAccess = "Get";
            if (actionContext.Request.Method == HttpMethod.Post) methodAccess = "Post";
            if (actionContext.Request.Method == HttpMethod.Put) methodAccess = "Put";
            if (actionContext.Request.Method == HttpMethod.Delete) methodAccess = "Delete";
 
            var isAuthorised = false;
            if (HttpContext.Current.Session.Count > 0)
            {
                isAuthorised = true;
            }
            return isAuthorised;
        }
    }
}


Filters run in the following order:
  1. Authorization filters
  2. Action filters
  3. Response filters
  4. Exception filters
For example, authorization filters run first and exception filters run last. Within each filter type, the Order value specifies the run order. Within each filter type and order, the Scope enumeration value specifies the order for filters. This enumeration defines the following filter scope values (in the order in which they run):
  1. First
  2. Global
  3. Controller
  4. Action
  5. Last

No comments :