Using HttpContext in controller constructor

眉间皱痕 提交于 2019-12-24 00:44:31

问题


I was trying to set a property in the constructor af a controller like this:

public ApplicationUserManager UserManager { get; private set; }
public AccountController()
    {
        UserManager = HttpContext.GetOwinContext().Get<ApplicationUserManager>("");
    }

But as explained here:

https://stackoverflow.com/a/3432733/1204249

The HttpContext is not available in the constructor.

So how can I set the property so that I can access it in every Actions of the Controller?


回答1:


You can move the code into a read-only property on your controller (or a base controller if you need it available across your entire application):

public class AccountController : Controller {
    private ApplicationUserManager userManager;

    public ApplicationUserManager UserManager {
        if (userManager == null) {
            //Only instantiate the object once per request
            userManager = HttpContext.GetOwinContext().Get<ApplicationUserManager>("");
        }

        return userManager;
    }
}


来源:https://stackoverflow.com/questions/24342887/using-httpcontext-in-controller-constructor

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