C# .NET: Microsoft MVC .NET: Create Custom MVC Filter

12/17/2013 4:43:20 PM

MVC Filters allow you to control access to controllers. A common filter is the [Authorize] filter that can be applied to any controller or action to restrict access to only authenticated users. The following is a basic filter that would restrict access to only System Administrators. The IsSystemAdministrator logic would have to be deteremined elsewhere.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyWebsite.MVCFilters
{
    public class SystemAdministratorFilter : AuthorizeAttribute
    {
        public SystemAdministratorFilter()
        {            
        }


        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

			//logic for allowing access or not
            bool allow = Helpers.IsSystemAdministrator;

            if (allow)
            {
                return;
            }
            else
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
    }
}



//Use of filter on controller or action
[MyWebsite.MVCFilters.SystemAdministratorFilter]
public ActionResult List_All_Users()
{
......