HttpContext.Current.User is null in ControllerBase(asp.net mvc)

纵饮孤独 提交于 2019-12-10 03:09:22

问题


I have a ControllerBase class in an ASP.NET MVC Application. The other controllers inherit from ControllerBase.

I want to access HttpContext.User.Identity.Name, but HttpContext is null. What's the matter?

public ControllerBase()
        {
            var dataManager=new DataManager();
            if (HttpContext.User.Identity.IsAuthenticated) // throws error
            {                    
                ViewData["assets"] = ud.BalanceFreeze + ud.Balance + ud.BalanceRealty;
                ViewData["onaccount"] = ud.Balance;
                ViewData["pending"] = ud.BalanceFreeze;
                ViewData["inrealty"] = ud.BalanceRealty;
            }

回答1:


Try adding your code to this event in your ControllerBase:

protected override void Initialize(RequestContext requestContext){

}



回答2:


Your controller gets constructed before the HttpContext has been set by ASP.NET. Like Nik says, you need to put this code into an overridden method in your class.

I would also point out that depending on HttpContext directly will make it impossible to perform unit testing on any of your controllers that extend this class. This is why many of the methods (like the Execute method) in the ControllerBase class take a RequestContext as an argument. You can say:

protected override void Execute(System.Web.Routing.RequestContext requestContext)
{
    var currentUser = requestContext.HttpContext.User;
    ...
}

... which makes it possible to create and execute your controllers with "fake" contexts for unit testing purposes.



来源:https://stackoverflow.com/questions/3704284/httpcontext-current-user-is-null-in-controllerbaseasp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!