Loading ...

ASP.NET MVC 3: Global action filters | CodeAsp.Net

ASP.NET MVC 3: Global action filters

 /5
0 (0votes)

If you need to perform some custom logic before displaying each view, you should create and register a global action filter.

Global action filters are applied to all actions in web application.

Steps to create a Global Action Filter:

1. Add a new folder to your Mvc project called "Filters"

2. Create a class named "LoadedTimeStampActionFilter" that inherite from ActionFilterAttribute in "Filters" folder

Note: We have 4 methods that are called from MVC framework that can be overridden 

OnActionExecuted - after the action method executes.
OnActionExecuting - before the action method executes.
OnResultExecuted - after the action result executes.
OnResultExecuting - before the action result executes.

For this example we will override OnActionExecuted and we will write to the HTTPContext.Response the time that our action was last executed.

    public class LoadTimeStampAcctionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.RequestContext.HttpContext.Response.Write(DateTime.Now.ToShortTimeString());
            base.OnActionExecuted(filterContext);
        }
    }

3. Now we should register this filter to RegisterGlobalFilters method in Global.asax

public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new LoadTimeStampAcctionFilter()); //Here
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
    }


Now we can run the application and and view the source  - we will see that we have the time in our source code:

7:35 PM<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
    <link href="/Content/Site.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <div id="header">
            <div id="title">
                <h1>My MVC Application</h1>
            </div>

Note: Also you can register global action filers by configuration. For that approach please check this post 

You can use global filters for different purposes like establishing global security policies,controlling output and etc.

Hope you find it usefull :)

Attachments

Comments (no comments yet)

  • :*
  • :*
  • :
 *

Top Posts