【问题标题】:Alternate of GetUserManager in asp.net core在 asp.net 核心中 GetUserManager 的替代品
【发布时间】:2020-01-25 13:35:22
【问题描述】:

我正在将现有的 Asp.net Mvc 项目转换为 .Net Core,现在问题是这个 get 方法

public ApplicationUserManager UserManager
    {
        get
        {



return _userManager ??
HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

        }
        private set
        {
            _userManager = value;
        }
    }

在 Mvc 中,我们可以使用

获取 OwinContext

HttpContext.GetOwinContext().GetUserManager()

但如果 .Net Core GetOwinContext 不存在,当我比较两个类的 HttpContext 定义时

HttpContextBase 在 Mvc 的情况下是类型,但在 Core 的情况下,HttpContext 在与 HttpContextBase 相同的命名空间中没有扩展方法,这就是为什么找不到此扩展方法的原因,请告诉我如何在 Core 中执行此操作?

【问题讨论】:

标签: c# asp.net-mvc asp.net-core owin


【解决方案1】:

没有替代品。 ASP.NET Core 对几乎所有东西都使用依赖注入。如果你需要UserManager&lt;TUser&gt;,你可以注入到你正在使用的任何类(控制器等)的构造函数中:

public class MyController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public MyController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    ...
}

【讨论】:

  • 非常感谢您的宝贵时间和帮助
  • 是否保证UserManager会出现在服务提供者中?
【解决方案2】:

要从HttpContext 访问UserManager,您可以尝试实现如下扩展:

public static class HttpContextExtension
{
    public static UserManager<TUser> GetUserManager<TUser>(this HttpContext context) where TUser: class
    {
        return context.RequestServices.GetRequiredService<UserManager<TUser>>();
    }
}

然后像这样使用它

public class HomeController : Controller
{        
    public IActionResult Index()
    {
        var userManager = HttpContext.GetUserManager<IdentityUser>();
        return View();
    }       
}

【讨论】:

  • 非常感谢您的宝贵时间和帮助
  • 实际上@ChrisPratt 只回答了这个问题,我只是忘了接受
  • @TAHASULTANTEMURI 请接受解决您问题的答案。
猜你喜欢
  • 1970-01-01
  • 2019-10-11
  • 1970-01-01
  • 2020-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多