Filters in MVC5?

Filters: Filters in mvc are a way to implement cross cutting concerns which means Functionaity that is used aross the application based on different layers. These fnctionality includes logging, exception handling, cacheing, Authorization, Authentication etc.

These function are required to kept at single place so as to mkae changes easier.Advavntage that filters provide as they use common logic to implemented using cross cutting concerns that can be applied on different controllers and action methods.

There are generally two types of filters that are Global filters and Controller filters. 

We can create a Global filter by creating a class nad registering it as a global filter 
<code>
public class DemoGlobalFilterAttribute : ActionFilterAttribute
   {
       public override void OnActionExecuting(ActionExecutingContext context)
       {
           base.OnActionExecuting(context);
           context.RequestContext.HttpContext.Response.Write("This is global filter");
       }
   }
</code>

Then register global filter
<code>
GlobalFilters.Filters.Add(new TestGlobalFilterAttribute());
</code>

Similary we can do for Controller Filters.


Filter Overrides in MVC 5: 
MVC5 gives a feature of filter override which can be applied to controllers and action methods which can override the golbal filter or the controller filter for the specified controller or the action method.

lets take a small example we want to override the contactus action method in the home controller.for this we only need to apply the OverrrideActionFilter attrinbute on the action method.Check the code below. 
<code>
[OverrideActionFilters]
public ActionResult ContactUs(){
ViewBag.Message = "This is the contact us page";
return View();
}
</code>
This can be usefull in different and multiple scenarios, Lets see a small scenario.
<code>
[Authorize(Users="Demo")]
[RoutePrefix("Prod")]
public class ProdController : Controller  
 {

[Route("Mob/{categoryId:maxlength(8)}")]
[OverrideAuthorization]
public ActionResult GetMobiles(string categoryId)
{    
    ViewBag.categoryId= t;      
    return View();
}
</code>

Here we have applied the authorize filter to the controller, then overridden the controller filter on GetMobiles action action method

We have filter overrides for each filter types
OverrideActionFilter         -  ActionFilter
OverrideAuthorizationFilter  -  AuthorizationFilter
OverrideAuthenticationFilter -  authenticationFilter
OverrideExceptionFilter      -  ExceptionFilter

Comments

Popular posts from this blog

Start working with CDS in Power Platform

Understanding of Power Query

Power Apps Choice Column Default Value with connector as Sharepoint