Mvc Filter

Last modified on May 08th, 2020 by DigitalIndiaInfo Team.


Filter in Mvc

You have learned how to use viewbag ,viewdata and tempdata the previous section. Here, you will learn what is filter in mvc and how will i use it inside application.

Filters is most important concepts in mvc,Filter is a special type trigger , An action filter is an attribute that you can apply to a action method or whole controller , it execute before or after on action method calling. its depend on user logic.mvc filter is a custom class. inwhich you can write user define logics to execure before and after action method.

Filter can be applied on action method or controller level or global lebel also.

Mvc Provide different types of filter such as

  1. Authorization filters
  2. Action filters
  3. Result filters
  4. Exception filters

MVC Filters are used to perform some common functionalities in application.

  1. Authorization and Authentication (in mvc5)
  2. Caching
  3. Logging
  4. ValidateInput
  5. RequireHttps
  6. Error Handling , etc.

Action filter are also use different types

OutputCache

We need caching in many different ,if we want to improve webpage loding ,or we do not want every time it request to server for same page so here we can use caching. it main feature is speed up the web page,server load reduce .here you can define caching time on action method,controller level or globally.

[OutputCache(Duration = 160)] public ActionResult home(){ var student = from e in db.students orderby e.ID select e; return View(student); }

Cache Profile

HandleError

This action filter handles errors raised when a controller action executes.

Authorize

This action filter enables you to restrict access to a particular user or role.

How will Add the filters in ASP.NET MVC?

you can add three different levels of our application. They are as follows

  • Action Level
  • Controller Level
  • Global Level
Action Level
                    
 public class EmployeeController : Controller
{
    [Authorize(Users = "admin,User2")]
    public ActionResult Showdetail(string id)
    {
        // You logic
        return View();
    }
}
 
  
Controller Level

                    
[Authorize(Roles = "Administrator")]
public class AdministratorController : Controller
{
    //You logic
}
                    
                
Global Level

                    
protected void Application_Start()
{
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
                    
                
Example: StyleBundle

    

                        

Learn how to set image path in StyleBundle.

Points to Remember :
  1. Use Styles.Render("bundle name") method to include style bundles in a razor view.


References :

  • www.tutorial.digitalindiainfo.com