我如何在 ASP.net 中使用 ApplicationUserManager?

How could I use ApplicationUserManager in ASP.net?

我在我的应用程序中创建了一个名为 ProfileContoller 的控制器。 在此控制器中,我需要创建 ApplicationUserManager 的实例,但我不知道如何创建它的新实例。我试过下面的代码:

private ApplicationUserManager _userManager = Current.GetOwinContext().GetUserManager<ApplicationUserManager>();

但是我得到了这个错误:

The name Current does not exist in the current context

我的第一个问题是我该怎么做?我将访问这行代码:

return View(await _userManager.FindByNameAsync(username));

我也用一个UnityContainer。我的第二个问题是:我是否也可以注册与接口 IUserIUserStore1.

关联的 ApplicationUserManager

更新:

后来我发现是这样的:

private UserManager<ApplicationUser> _userManager = UserManager<ApplicationUserManager>();

它给我这个错误:

Non-invocable member UserManager<TUser> cannot be used like a method.

有了这个额外的"user manager",我见树不见林。那么你能再一次解释一下所有 "user managers" 的含义以及它们的用途吗?


备注:
1我不知道这两者之间的区别所以如果你愿意,你能解释一下吗?

我没有在 VS 中查看过这个所以不是 100% 但是你收到的错误消息

The name Current does not exist in the current context

可能只是因为当前是 http 上下文的一部分

尝试

public class ProfileController : Controller
{

    private ApplicationUserManager _userManager;

    public ProfileController()
    {
        _userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
    }

所以这里的变化是声明了_userManager但没有设置。 然后我们在 class.

的构造函数中设置它

这对我有用:

using System.Web;  //make sure you have this using

    private ApplicationUserManager _userManager;
    public ApplicationUserManager UserManager
    {
        get
        {
            if (_userManager == null && HttpContext == null)
            {
                return new ApplicationUserManager(new Microsoft.AspNet.Identity.EntityFramework.UserStore<ApplicationUser>(db));
            }
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }