【问题标题】:Using HttpContext in controller constructor在控制器构造函数中使用 HttpContext
【发布时间】:2014-06-21 15:05:12
【问题描述】:
我试图在控制器的构造函数中设置一个属性,如下所示:
public ApplicationUserManager UserManager { get; private set; }
public AccountController()
{
UserManager = HttpContext.GetOwinContext().Get<ApplicationUserManager>("");
}
但正如这里所解释的:
https://stackoverflow.com/a/3432733/1204249
构造函数中没有HttpContext。
那么如何设置属性,以便在Controller的每个Action中都可以访问它呢?
【问题讨论】:
标签:
asp.net-mvc
asp.net-identity-2
【解决方案1】:
您可以将代码移动到控制器上的只读属性中(或者如果您需要在整个应用程序中使用基本控制器):
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;
}
}