Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

What are Action Filters in ASP.NET MVC

In the previous article, you learned about What is Filters in MVC?. Now, you will learn about another filter type called Action Filters in MVC. Keep reading on ASP.NET MVC full Ajaxify and Bootstrap Grid with Crud Operation.

Why do we use Action Filters in MVC

Action filter executes before and after an action method executes. Action filter attributes can be applied to an individual action method or to a Controller. When an action filter applied to the controller then it will be applied to all the action methods in that controller.

There are three types of Action Filters in MVC:-

  • OutputCache

OutputCache is a built-in action filter attribute that can be applied to an action method for which we want to cache the output. For example, the output of the following action method will be cached for 30 seconds.

public class LoginController : Controller
    {
        // GET: Login
        [OutputCache(Duration =30)]
        public ActionResult Index()
        {
            return View();
        }
    }
  • HandleError

It handles the error caused by action or controller, if any exception occurs it redirects the action to the custom error page. Find the below code snippet to handle the error attribute is decorated to the login action method, it will redirect to a view called “Error.cshtml” when any exception will occur by this action method.

public class LoginController : Controller
    {
        // GET: Login
        [HandleError (View="Error.cshtml")]
        public ActionResult Index()
        {
            return View();
        }
    }
  • Authorize

This action filter enables you to restrict access to a particular user or role. It is used for filtering the authorized user to access the resource. Find the below source code I have declared an action method with [Authorize] attribute.

public class LoginController : Controller
   {
       // GET: Login
       [Authorize]
       public ActionResult Index()
       {
           return View();
       }
   }
Authorize Filter Output

Conclusion

I hope you liked this article on action filters in MVC 5. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

The post What are Action Filters in ASP.NET MVC appeared first on DotNetTec.



This post first appeared on Asp Dot Net Tricks And Tips, Dot Net Coding Tips, Google Maps API Developer, please read the originial post: here

Share the post

What are Action Filters in ASP.NET MVC

×

Subscribe to Asp Dot Net Tricks And Tips, Dot Net Coding Tips, Google Maps Api Developer

Get updates delivered right to your inbox!

Thank you for your subscription

×