【问题标题】:How could I use ApplicationUserManager in ASP.net?如何在 ASP.net 中使用 ApplicationUserManager?
【发布时间】:2016-05-26 17:26:46
【问题描述】:

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

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

但我收到了这个错误:

名称Current在当前上下文中不存在

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

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

我也使用UnityContainer。我的第二个问题是:我是否也可以注册与接口IUserIUserStore 关联的ApplicationUserManager1


更新:

后来我发现有这样的东西:

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

它给我这个错误:

不可调用的成员UserManager&lt;TUser&gt; 不能像方法一样使用。

有了这个额外的“用户管理器”,我就看不到树木了。那么您能再解释一下所有“用户管理器”的含义以及它们的用途吗?


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

【问题讨论】:

  • 你有正确的 using 语句吗? stackoverflow.com/questions/24001245/…
  • 关于cannot be used like a method 的嗯——你错过了new 关键字吗? -- 看起来你确实在尝试调用一个像方法一样的类型......

标签: c# asp.net entity-framework unity-container user-management


【解决方案1】:

这对我有用:

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;
        }
    }

【讨论】:

  • ApplicationUserManager 类型从何而来? -- 默认不存在;你在某个地方有一个名为这个的类吗? -- 在这种情况下,您的 _userManager 缓存值也永远不会被设置,也许您应该先设置它而不是只返回值,然后将其作为第二步返回。
【解决方案2】:

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

名称 Current 在当前上下文中不存在

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

试试

public class ProfileController : Controller
{

    private ApplicationUserManager _userManager;

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

所以这里的变化是 _userManager 被声明但未设置。 然后我们在类的构造函数中设置它。

【讨论】:

  • 不,对不起。现在我遇到了这个错误 A field initializer cannot reference the non-static field, method, or property Controller.HttpContext
  • 我已经编辑了一个我认为会有所帮助的更新。
  • 我也不工作。我有这个错误'IOwinContext'不包含'GetUserManager'的定义,并且找不到接受'IOwinContext'类型的第一个参数的扩展方法'GetUserManager'(您是否缺少使用指令或程序集参考?)GetUserManager&lt;ApplicationUserManager&gt;().
  • 在这种情况下,您在某处缺少引用 - GetOwinContext 是 Microsoft.Owin 命名空间中的扩展方法。确保您引用了 Microsoft.Owin、Microsoft.Owin.Host.SystemWeb 和 Microsoft.Owin.Security。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-17
  • 2015-11-24
  • 1970-01-01
  • 2017-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多