Getting User Identity on my base Controller constructor

前端 未结 2 948
伪装坚强ぢ
伪装坚强ぢ 2020-12-11 04:40

I have a base Controller on my ASP.NET MVC4 website that have a Constructor simple as this:

public class BaseController : Controller
{
    protected MyClass          


        
相关标签:
2条回答
  • 2020-12-11 05:01

    Controller instantiation will occur before authorisation takes place. Even if your MVC application calls RenderAction() several times and you end up creating say, five different controllers, those five controllers will be created before any OnAuthorization takes place.

    The best approach to deal with these situations is to use Action Filters. The Authorize Attribute is fired early and may well be suited to your situation.

    First, let's create an AuthorizationFilter.

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class MyClassAuthorizationAttribute : Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Controller.ViewData["MyClassInstance"] = new MyClass();
            }
        }
    }
    

    Now let's update our Controller

    [MyClassAuthorization]
    public class BaseController : Controller
    {
        protected MyClass Foo
        {
            get { return (MyClass)ViewData["MyClassInstance"]; }
        }
    }
    
    0 讨论(0)
  • 2020-12-11 05:14

    In this case I would override Controller Initialize method:

    protected override void Initialize(RequestContext requestContext)
    {
       base.Initialize(requestContext);
       // User.Identity is accessible here
    }
    
    0 讨论(0)
提交回复
热议问题