gpt4 book ai didi

asp.net - 将 System.Web.HttpContext.Current 转换为 System.Web.HttpContextBase

转载 作者:行者123 更新时间:2023-12-04 13:13:06 26 4
gpt4 key购买 nike

我需要从我的 Controller 之一的构造函数中访问 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是同一个 Controller 的属性,它看起来像这样:
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实例,为空。

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

所以,我想知道我是否可以获得对 OwinContext 的引用。直接使用 System.Web.HttpContext.Current属性(property)。但是,该属性的类型是 System.Web.HttpContext其中 GetOwinContext是类型 System.Web.HttpContextBase 上的扩展方法我看到这两个类彼此没有任何关系。

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

最佳答案

就在这里:

HttpContextBase httpContext = new HttpContextWrapper(HttpContext.Current);

是的, HttpContext在构建 Controller 期间,属性始终为空。您可以在 Controller.Initialize method 中(和之后)安全地使用它.

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

关于asp.net - 将 System.Web.HttpContext.Current 转换为 System.Web.HttpContextBase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38237129/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com