在控制器构造函数中使用HttpContext

3

我试图在控制器的构造函数中设置属性,就像这样:

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

但是如下所述:

https://dev59.com/knA75IYBdhLWcg3wK10p#3432733

在构造函数中HttpContext不可用。

那么我该如何设置属性以便在控制器的每个操作中都能访问它?

1个回答

5
你可以将代码移动到控制器的只读属性中(如果需要在整个应用程序中使用,则可以放在基本控制器中):
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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接