Wednesday, November 8, 2017

how to control the page access in the controller level in MVC web application?

we can control the page access in various area in the MVC web applicaton.

first we can control in the razor page file.

@if (!this.User.HasPermission(ADGroup))
{
    Response.Redirect("~/ErrorMessage.aspx?ErrorCode=AccessDenied");
}

second we can control access in the Action method.
 public async Task<ActionResult> MyPage()
        {
         if (!IsAllowAccess)
       {
           return Redirect("~/ErrorMessage.aspx?ErrorCode=AccessDenied");
       }
    }

third we can set the access permission in the Class level by implmented an ActionFilterAttribute.


 public class MyPageAccessActionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!IsAllowAccessPage)
            {
                filterContext.Result = new RedirectResult("~/ErrorMessage.aspx?ErrorCode=AccessDenied");
            }
            base.OnActionExecuting(filterContext);
        }
    }


Then in Page Controller, I can just set the  MyPageAccessActionFilter Attribute in controller class
   [MyPageAccessActionFilter]
    public class MyController : Controller
    {

}

the third approach will reduce lots of code and affect on the maintenance. since we can easily modify one file to apply permission on the action methods within the controller.














No comments:

Post a Comment