In Web Development
0
118

Hey Guys, I have come back with another new blog and with an overwhelming topic i.e. How to use Filters in ASP.Net MVC in our application.

Most importantly, I am very thankful to all of you that you are reading my blogs very well and I promise that this blog will also be a good source of knowledge for you.

In this Blog, I will explain you each and every topic related to filters and how to use them. If you don’t know what is MVC, then I’ll also describe this. MVC is a Model View Controller and it is an architecture pattern that separates an application into three main components:

  1. Model
  2. View
  3. Controller

let’s take a look into the diagram for a better understanding of how MVC works in our application.

Model-View-Controller(MVC)

Model: In MVC, Model handles all logic sections in our application. For Example, a request from a user to insert or retrieve data from the database.

View: We create Views from Model and are the UI that we look into the application.

Controller: Controller controls the flow of an application and a set of classes that handles communication from the user, overall application flow, and application-specific logic.

Now, let me tell you about the filters in MVC and how to use them in our application in Visual Studio.

What are Filters in MVC?

If we talk about day-to-day life, Filter is a common word. A filter is just a kind of device that you can use to remove unwanted or dirty stuff from something.

In MVC, this logic is same as Filters are the custom classes where we can put or write our logic to execute before or after an action method executes. Let me explain in simple terms, suppose we want to execute an action method before any method execute. So, we apply filters to that action method which we want before execution. We can apply filters to an action method or Controller in a declarative and programmatic way.

In this, Declarative means by applying a filter attribute to an action method or controller class.

and, Programmatic means by implementing a corresponding interface.

Types of Filters in MVC

In ASP.NET MVC, there are different types of filters available. Let me describe you one by one in a theoretical and practical way & these filters run in the following order.

1. Authorization FIlter

2. Action Filter

3. Result Filter

4. Exception Filter

Authentication Filter: This filter is introduced in MVC 5. I have also defined this filter to you guys after all these 4 filters completed.

Filter TypeInterfaceDescription
Authorization FilterIAuthorizationFilterThese Runs first, before any other filters or the action method.
Action FilterIActionFilterThese Runs before and after the action method.
Result FilterIResultFilterRuns before and after the action result is executed.
Exception FilterIExceptionFilterRuns only if another filter, the action method, or the action result throws an exception.

How to use Different filters in MVC

1. Authorization Filter

Let’s start with authorization filter, these are the filters that run before any other filters (Action, Result, Exception) executed. If we talk about its functionality it verifies “What to do” means you have a capability or permission to do (or not to do) that thing. One thing you can notice that Authentication filters (Introduced in MVC 5) run prior to authorization filter. As the name implies,

  • It Enforce authorization policy.
  • Invoked only by the approved(Authorized) users.
  • It implements IAuthorizationFilter interface.
namespace used System.Web.Mvc {
interface used IAuthorizationFilter {
// It has a method named
void OnAuthorization(AuthorizationContext filterContext)
}
}

The Example shows clearly how we use Authorization Filter in our application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFilters_Demo.Controllers
{
public class HomeController : Controller
{
[Authorize(Users ="mohd,ameeq")]
public ActionResult Index()
{
return View();
}
}
}

 Now, we are going to make a new class that is derived from the AuthorizeAttribute class.

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
   Entities context = new Entities(); // create entity object
   private readonly string[] allowedroles;
   public CustomAuthorizeAttribute(params string[] roles)
   {
      this.allowedroles = roles;
   }
   protected override bool AuthorizeCore(HttpContextBase httpContext)
   {
      bool authorize = false;
      foreach (var role in allowedroles)
      {
         var user = context.AppUser.Where(m => m.UserID == GetUser.CurrentUser && m.Role == role &&
         m.IsActive == true);
         if (user.Count() > 0)
         {
            authorize = true; /* it returns true if user is active */
         }
      }
      return authorize;
   }
   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
   {
      filterContext.Result = new HttpUnauthorizedResult();
   }
}

2. Action Filter

Let’s start with the Action filter attribute and I am showing you the practical demo for how to create a new project in MVC.

Step 1:

first of all, Open a Visual Studio and click on File-> New-> and click on Project menu option.

A New Dialog box opens like

Step 2:

On the left side pane, select Web from the templates.

Step 3:

In the Middle section of a window, Click -> ASP.NET Web Application.

Step 4:

In the next step, we select the location of a project and give a proper name of the project and then click OK and after that, a new dialog box opens

Step 5:

In this Step, we will select the Empty option from the Dialog box and check the MVC checkbox among all the checkboxes and then click on OK and it will take some time to create a new project.

Step 6:

The project creation work has been completed and we will try to add a Controller to our project. For this, Right click ->Controller->Add-> and click on Controller.

And a new Dialog box has shown at our UI.

Controller Add Scaffold Dialog

Step 7:

We will select “MVC 5 Controller- Empty” and click on Add. A new PopUp window has opened look likes. We give a meaningful name to our Controller HomeController and click on Add.

Add Controller Dialog

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ActionFilterDemo.Controllers
{
public class HomeController : Controller
{
// GET: Home
[OutputCache(Duration = 20)]
public string GetMessage()
{
return "Thanks for reading my Blog... Regards Ameeq";
}
}
}

Step 8:

Finally, we run this application by pressing f5 or click on Debug -> Start Debugging. The output window has shown looks like.

Request for the Url: http://localhost:XXXXX/ControllerName/ActionMethodName

Example for the Url: http://localhost:41463/Home/GetMessage

Action filter doesn’t directly implement IActionFilter instead it implements ActionFilterAttribute. If we want to look into the code then just Right Click-> and press ->go to definition.

namespace System.Web.Mvc
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class OutputCacheAttribute : ActionFilterAttribute, IExceptionFilter
}

And if we want to know exactly what’s the method call in ActionFilterAttribute then we press f12.

namespace System.Web.Mvc
{
// Represents the base class for filter attributes.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public abstract class ActionFilterAttribute : FilterAttribute, IActionFilter, IResultFilter
{
amy();
}
}

And, two methods that are used in Action Filter.

 // Defines the methods that are used in an action filter.
 public interface IActionFilter
{
// Called after the action method executes.
void OnActionExecuted(ActionExecutedContext filterContext);
 // Called before an action method executes.
void OnActionExecuting(ActionExecutingContext filterContext);
 }

3. Result Filter

Now, I am going to tell you about Result filters in MVC. Result filters are basically used for logging the exceptions that occurred in our application when a view is executed. So basically, Result filter plays an important role when we logged the exceptions.

  1. It implements IResultFilter interface.
  2. IResultFilter has 2 methods: OnResultExecuting and OnResultExecuted

OnResultExecuting is executed before the ActionResult is executed.

OnResultExecuted is executed after the ActionResult.

 public override void OnResultExecuted(ResultExecutedContext filterContext)    
  {    
      Log("OnResultExecuted calls", filterContext.RouteData);          
  }    
    
  public override void OnResultExecuting(ResultExecutingContext filterContext)    
  {    
      Log("OnResultExecuting calls", filterContext.RouteData);          
  }

Let’s understand this with the help of a small example. I am showing you only the main class ResultF.cs and Controller class HomeController.cs of how to implement Result filter in our application.

ResultF.cs file

using System;
using System.Collections.Generics;
using System.Web;
using System.Web.Mvc;
using WebAppDemo.Models;
namespace WebAppDemo.FilterEx
{
      public class ResultFilter:FilterAttribute,IResultFilter
      {
         DatabaseContext db=new DatabaseContext();
          public void OnResultExecuted(ResultExecutedContext filterContext)    
          {    
               db.logs.Add(new log()
               {
                  ActionName=filterContext.RouteData.Values["action"].ToString(),
                  ControllerName=filterContext.RouteData.Values["controller"].ToString(),
                  var abc=DateTime.Now,
                   var xyz="AmeeqTestResultExceuted"
               });
                 db.SaveChanges();
           }  
          public void OnResultExecuting(ResultExecutingContext filterContext)    
          {    
               db.logs.Add(new log()
               {
                  ActionName=filterContext.RouteData.Values["action"].ToString(),
                  ControllerName=filterContext.RouteData.Values["controller"].ToString(),
                  var abc=DateTime.Now,
                   var xyz="AmeeqTestResultExceuting"
               });
                 db.SaveChanges();
           } 
}
}

HomeController.cs

public class HomeController:Controller
{
[ActionFilter,ResultFilter]
public ActionResult Index() {
return View();}
}

This is the practical demo of how to implement ResultFilter.

4. Exception Filter

Here, I will describe you about Exception filters in MVC. This type of filters runs only if an unhandled or runtime exception has been thrown when we invoke or call an action method. In our application, the exception can occur due to the following reasons:

  • When we try to execute the action result.
  • the action method calls itself.

It implements IExceptionFilter interface to invoke the methods.

public interface IExceptionFilter
{
void OnException(ExceptionContext filterContext);
}

Now I am going to tell you about in detail of how we use Exception Filter in our application.

1. Open Visual Studio and click on File-> and click on New-> and click on Project menu option.

2. Give a proper name of a project and save it in the respective location.

3. Create a class, Right click on ProjectName in the right pane -> Add -> Class and named it

MyException.cs. The code is given below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFilters_Demo
{
public class MyException:FilterAttribute,IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
}
}
}

4. In the Next Step, We are going to add a new Controller and name HomeController.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFilters_Demo.Controllers
{
[MyException]
public class HomeController : Controller
{
public ActionResult Index()
{
try
{
int a = 100;
int b = 0;
int c = a / b;
}catch(Exception ex)
{
Console.WriteLine("Error thrown");
}
return View();
}
public ActionResult About()
{
ViewBag.Message = "Mohd Ameeq is a DotNet Developer";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Noida,India";
return View();
} 
}
}

After this, we run the application and the output screenshot is as follows:

Now, I am going to explain Authentication Filter.

Authentication Filter

This is a new filter in MVC that is introduced in MVC 5. This filter runs before any other filter run or we can say it is a Parent filter of all other filters that we have used so far like Authorization, Action, Result, Exception filters.

In this type of filter, we authenticate user which was not available in older versions of MVC[MVC 4]. For using this filter we need to implement IAuthentication Filter.

It has two methods:

  1. OnAuthentication
  2. OnAuthenticationChallenge.

OnAuthentication: In this, we are going to authenticate the request.

OnAuthenticationChallenge: This method is called when authentication or authorization failed. Another important point is that it is called after the action method has executed but before rendering of view.

Now, for better understanding Let’s create a project and see the demo.

After setting the name of a project then click on OK button and click on MVC -> OK.

Our new project looks like:

Now we have to create a new folder inside our project. For this, we need to right click on project name and click on Add->New Folder and name it as Filters.

After creating the folder we need to add class inside this and name it as UserAuthenticationFilterDemo.cs.

Now we create the methods of Authentication filter in UserAuthenticationFilterDemo.cs class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
namespace MVCAuthenticationFilter_Demo.Filters
{
public class UserAuthenticationFilterDemo : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
// it will check Session if it is empty then it set the result as HttpUnauthorizedResult
if (string.IsNullOrEmpty(Convert.ToString(filterContext.HttpContext.Session["UserID"])))
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
// In this method We are trying to check Result is null or Result is HttpUnauthorizedResult 
// if yes then we are Redirect page to Error View
if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result = new ViewResult
{
ViewName = "Error"
};
}
}
}
}

In the next step, we are going to create a login page for authorization of valid user. For this, right click on Models->Add-> class and name it as LoginModelDemo.cs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace MVCAuthenticationFilter_Demo.Models
{
public class LoginModelDemo
{
[Display(Name="LoginName")]
[Required]
public string LoginName{ get; set; }
[Display(Name="LoginPassword")]
[Required]
public string LoginPassword{ get; set; }
}
}

Finally, we add a Controller and name it UserLoginControllerDemo.cs. The code looks like :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MVCAuthenticationFilter_Demo.Models;
using System.Web.Mvc;
namespace MVCAuthenticationFilter_Demo.Controllers
{
public class UserLoginControllerDemoController : Controller
{
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginModelDemo model)
{
if (!ModelState.IsValid)
{
return View(model);
}
else
{
if(model.LoginName == "Amy" && model.LoginPassword == "amy123")
{
Session["UserID"] = Guid.NewGuid();
return RedirectToAction("Index","Home");
}
else
{
ModelState.AddModelError("", "LoginName and Loginpassword invalid.");
return View(model);
}
}
}
}
}

After creating this, we add a View to our project. For this, Right Click on View->Add-> name it as Login and click on OK.

@model MVCAuthenticationFilter_Demo.Models.LoginModelDemo
@{
ViewBag.Title = "Login";
}
<h2>Login</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true, "Login failed. Please Check your details.");
<div>
<fieldset>
<legend>Login</legend>
<div class="editor-label">
@Html.LabelFor(u => u.LoginName)
</div>
<div class="editor-field">
@Html.TextBoxFor(u => u.LoginName)
@Html.ValidationMessageFor(u => u.LoginName)
</div>
<div class="editor-label">
@Html.LabelFor(u => u.LoginPassword)
</div>
<div class="editor-field">
@Html.PasswordFor(u => u.LoginPassword)
@Html.ValidationMessageFor(u => u.LoginPassword)
</div>
<input type="submit" value="Log In" />
</fieldset>
</div>
}

Applied Authentication Filter on Home Controller

Finally, we Check the code if it is valid or not for this, we applied authentication filter on HomeController.cs.

I am going to run this project and provide login details to validate the user and redirect the page to the home controller if it has a valid user.

The Output shows the Home Controller if the username and password are valid.

Guys, I hope you understand all the Filters that are used in MVC. This technique is very useful for filtration of data when the view is executed. Filters are very important for those who are new in MVC and for experienced holders also. I hope this blog will be more valuable and important for a new learner. Thank you!

RECOMMENDED POSTS

Start typing and press Enter to search