Tuesday, July 16, 2013

Filter/Allow Roles without using ASP.NET MVC Membership Provider

Following code demonstrate how to filter roles that are allowed to execute an action without using ASP.NET membership provider.

Create a class that inherits from ActionFilterAttribute

public class RoleFilter : ActionFilterAttribute { 

 public override void OnActionExecuting(ActionExecutingContext filterContext) 
   if (GetCurrentUserRole() != "Admin")// Check the Role Against the database Value 
     filterContext.Result = new RedirectResult("~/Redirect/NoPermission"); 

In your controller action add the RoleFilter attribute.

[RoleFilter]//Check the Role, if not allowed redirect to NoPermission view
 public ActionResult Index() 
   return View(); 

That's it. Now only Admin users are allowed to execute the action Index.

1 comment:
Write comments
Recommended Posts × +