Search code examples
asp.netasp.net-mvcasp.net-mvc-4asp.net-mvc-5entitlements

How can I centralize entitlement logic in an asp.net-mvc controller?


I have an ASP.NET-MVC web site with a SQL Server back-end. I have a number of controller actions that require me to do an entitlement check.

Right now, I do this:

    public ActionResult SomeEntitledPage()
    {
        if (_myModel.IsMySiteAdminRole)
        {
            return View(new MyViewModel());
        }
        else
        {
            return View("NotEntitled", new NotEntitledViewModel(){Page = "[PageName]", SupportDG = "support@support.com"});
        }
    }

this works fine but it feels like I am duplicating this logic in a number of places.

What is the best way (attribute, etc) to have a number of entitlement controller action "secure" based on the below?

(Secure being that it checks the IsMySiteAdminRole and returns the "not Entitled" view if not entitled.

I also want to make sure I don't have a performance penalty on every page?


Solution

  • I prefer to use action filters for Entitlement / Privilege logic. The beauty of these filters is they can run AFTER the action method populates your Model.

    For Example:

    public class AdminOnlyFilterAttribute : ActionFilterAttribute
    {
          public override void OnActionExecuted(ActionExecutedContext filterContext)
          {
            if (!filterContext.Controller.ViewData.Model.IsMySiteAdminRole)
                {
                    filterContext.Result = new ViewResult
                    {
                        ViewName = "NotEntitled",
                        Model = new NotEntitledViewModel(){Page = "[PageName]", SupportDG = "support@support.com"}
                    };
                }
            base.OnActionExecuted(filterContext);
        }   
    }
    

    Action Filters allow you to selectively override your Controller's OnActionExecuted method.

    This attribute can be applied to a specific action or an entire controller. The result will depend on your model values and will change your View only.