在控制器构造函数中使用HttpContext [英] Using HttpContext in controller constructor

查看:317
本文介绍了在控制器构造函数中使用HttpContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

构造函数中没有HttpContext.

The HttpContext is not available in the constructor.

那么如何设置属性,以便可以在Controller的每个操作中访问它?

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

推荐答案

您可以将代码移到控制器(或基础控制器(如果需要整个应用程序中都可以使用)的只读属性)上:

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;
    }
}

这篇关于在控制器构造函数中使用HttpContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆