加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 将System.Web.HttpContext.Current转换为System.Web.

发布时间:2020-12-16 03:59:52 所属栏目:asp.Net 来源:网络整理
导读:我需要从我的一个控制器的构造函数中访问OwinContext,如下所示: protected SEMController(){ var currentUserIsAdmin = false; var currentUserName = System.Web.HttpContext.Current.User?.Identity?.Name; if (!string.IsNullOrEmpty(currentUserName))
我需要从我的一个控制器的构造函数中访问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;
}

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

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

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

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

所以,我想知道是否可以通过直接使用System.Web.HttpContext.Current属性来获取对OwinContext的引用.但是,该属性的类型为System.Web.HttpContext,其中GetOwinContext是System.Web.HttpContextBase类型的扩展方法,我发现这两个类彼此无关.

所以,我想知道是否有办法从System.Web.HttpContext.Current到System.Web.HttpContextBase?

解决方法

就在这里:

HttpContextBase httpContext = new HttpContextWrapper(HttpContext.Current);

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

Initializes data that might not be available when the constructor is called.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读