Pages

Monday 8 December 2014

Role based Access to MVC4 Action/Controller using Custom Attribute

Custom Attribute in mvc4: Here I created one Custom Attribute named "CustomUserTypeAttribute" which is used to check user type. If user type matches with restricted user type then only this will redirect user to assigned error page. To pass restricted user type I used one string variable named "UserLevel" and implemented it's "get set" property. And then I compared that with the current user level which is stored in session variable.

Custom Attribute class : using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Routing; using System.Web.Mvc; namespace AuthenticationModule.Web.Common { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class CustomUserTypeAttribute : ActionFilterAttribute { public string UserLevel { get; set; } public override void OnActionExecuting(ActionExecutingContext filterContext) { try { if(HttpContext.Current.Session["user_level"].ToString().Equals(UserLevel)) { RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary(); redirectTargetDictionary.Add("action", "ErrorPage"); redirectTargetDictionary.Add("controller", "Home"); filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary); } } catch(Exception) { throw; } } } }

Using following you can apply this action filter on any action or controller. Here I passed the on string argument named "UserLevel" with value 2 to the action filter.

[CustomUserType(UserLevel = "2")] public ActionResult Add() {

No comments:

Post a Comment