将System.Web.HttpContext.Current转换为System.Web.HttpContextBase

Wat*_* v2 6 .net asp.net asp.net-mvc asp.net-mvc-5

我需要从我的一个控制器的构造函数中访问OwinContext,如下所示:

protected SEMController()
{
    var currentUserIsAdmin = false;
    var currentUserName = System.Web.HttpContext.Current.User?.Identity?.Name;
    if (!string.IsNullOrEmpty(currentUserName))
    {
        var user = UserManager.Users
            .SingleOrDefault(u => 
            u.UserName.Equals(currentUserName, 
            StringComparison.InvariantCultureIgnoreCase));
        if (user != null)
        {
            currentUserIsAdmin = UserManager.IsInRole(user.Id, UserType.Admin);
        }
    }
    TempData["CurrentUserIsAdmin"] = currentUserIsAdmin;
}
Run Code Online (Sandbox Code Playgroud)

其中UserManager是同一控制器的属性,它看起来像这样:

public ApplicationUserManager UserManager
{
    get
    {
        if (_userManager == null)
        {
            _userManager = HttpContext.GetOwinContext()
                .GetUserManager<ApplicationUserManager>();
        }
        return _userManager;
    }
    private set
    {
        _userManager = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当代码在ctor中时HttpContext,它是Controller类的属性并且是类型System.Web.HttpContextBase而不是System.Web.HttpContext实例,则为null.

但是,无论如何,ASP.NET框架只是将信息从一个地方复制到另一个地方,他们将在稍后的某个时间点获得的信息将是相同的.

所以,我想知道我是否可以OwinContext通过直接使用System.Web.HttpContext.Current属性获得对该引用的引用.但是,该属性的类型是System.Web.HttpContext其中的GetOwinContext是该类型的扩展方法System.Web.HttpContextBase,我看到这两个类是没有办法的相互关系.

所以,我想知道是否有办法从获得System.Web.HttpContext.CurrentSystem.Web.HttpContextBase

Nig*_*888 17

就在这里:

HttpContextBase httpContext = new HttpContextWrapper(HttpContext.Current);
Run Code Online (Sandbox Code Playgroud)

是的,HttpContext在构建控制器期间始终为null.您可以在Controller.Initialize方法中(以及之后)安全地使用它.

初始化调用构造函数时可能不可用的数据.