This project is read-only.

Creating a custom filter (ASP.NET MVC 2 only)

To create a custom filter for usage globally needed implement your custom filter class with one or more interfaces which are the four types of ASP.NET MVC filters:
  • IAuthorizationFilter
  • IActionFilter
  • IResultFilter
  • IExceptionFilter
For more information about work Action Filter in general, you can read Understanding Action Filters of ASP.NET MVC tutorial.

Example of custom filter:
public class CustomFilter: IResultFilter, IAuthorizationFilter
{
    #region IResultFilter Members

    public void OnResultExecuted(ResultExecutedContext filterContext)
    {
        // Some logic here ...
    }

    public void OnResultExecuting(ResultExecutingContext filterContext) 
    {
        // Or here ...
    }

    #endregion

    #region IAuthorizationFilter Members

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        // May be here?
    }

    #endregion
}

In the example below demonstrated how we can use Dependency Injection in filter (But firstly needed correctly configure application, review Using a Fluent Filters with an IoC container of project documentation)

using System.Web.Mvc;
using Website.Core.Services;

namespace Website.Core.ActionFilters
{
    public class OldBrowserDetectionFilter: IAuthorizationFilter
    {
        #region DI members

        private readonly IErrorService _errorService;

        #endregion

        #region Constructor

        public OldBrowserDetectionFilter(IErrorService errorService)
        {
            _errorService = errorService;
        }

        #endregion

        #region IAuthorizationFilter Members

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.Browser.Browser == "IE")
            {
                if (filterContext.HttpContext.Request.Browser.MajorVersion < 7)
                {
                    _errorService.ShowOldBrowserPage(filterContext.HttpContext);
                }
            }
        }

        #endregion
    }
}

Last edited Jan 30, 2011 at 9:21 PM by banguit, version 16

Comments

No comments yet.