Using action filters in MVC to restrict access to controller/action

by HarrySayari 30. November 2010 05:52

What is an action filter?

Sometimes you want to perform logic either before an action method is called or after an action method runs. To support this, ASP.NET MVC provides action filters. Action filters are custom attributes that provide a declarative means to add pre-action and post-action behaviour to controller action methods. (From MSDN) More

How to implement a custom action filter

  1. Inherit the abstract class ActionFilterAttribute and override the desired methods:
public class AdminAuthorize : ActionFilterAttribute
{
     public override void OnActionExecuting(ActionExecutingContext filterContext)
     {
           if (CheckYourConditon)
           { 
// executing action
base.OnActionExecuting(filterContext);
}
else
{
// Redirect to the needed login page or whatever you want
// This can be pulled from config file or anything else
filterContext.HttpContext.Response.Redirect("/error?ReturnUrl="
+ HttpUtility.UrlEncode(filterContext.HttpContext.Request.RawUrl));
}
}

}

  1. Add the custom attribute to your controller/action

Controller:

[AdminAuthorize]
public partial class SendEmailController : Controller
{
...
}

Action:

[AdminAuthorize]
public virtual ActionResult Reset()
{
...
}

Membership integration

If you using ASP membership you can use Authorize attribute easily. You can use that to restrict the access to an action or a controller like this:

[Authorize(Roles="Admins")]

Or

[Authorize(Users="Admin")]
Tags:
Categories: .Net

Comments

11/30/2010 5:02:30 PM #

great
By using this thechnic we can provide some generale parameters and check this params befor runing action.
for example we can provide lang parameter for changing language in multi language sites. and then execute action

Navid Iran

12/21/2010 1:35:30 PM #

Pretty interesting stuff you have here, to say the least..

Flinyn People's Republic of China