UserManager<XYZ>”不包含“CreateIdentityAsync”的定义并且没有可访问的扩展方法

Sye*_*ama 4 c# asp.net-identity asp.net-core-mvc asp.net-core

我正在使用 asp.net mvc core 2.1 版本,在 ApplicationUser 类中添加属性时收到这两个错误,并且在这段代码上收到错误:

 var userIdentity = await manager.CreateIdentityAsync(this,DefaultAuthenticationTypes.ApplicationCookie);
Run Code Online (Sandbox Code Playgroud)

我正在尝试修复过去 3 天的错误:

“UserManager”不包含“CreateIdentityAsync”的定义,并且找不到接受“UserManager”类型的第一个参数的可访问扩展方法“CreateIdentityAsync”(您是否缺少 using 指令或程序集引用?)

“名称‘DefaultAuthenticationTypes’在当前上下文中不存在”

我的班级如下

 public class ApplicationUser:IdentityUser
    {


       public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            var userIdentity = await manager.CreateIdentityAsync(this,DefaultAuthenticationTypes.ApplicationCookie);
            return userIdentity;
        }

        public string FullName { set; get; }

        public string MobileNumber { get; set; }

        public int CountryId { get; set; }

        public int StateId { get; set; }

        public int CityId { set; get; }

        public string Address { get; set; }

        public string ShippingAddress { get; set; }

    }
Run Code Online (Sandbox Code Playgroud)

itm*_*nus 5

不确定为什么您需要在实体ClaimsIdentity内生成 a ApplicationUser,它应该是POCO. 据我所知,最好将其移到其他地方。

如果您确实想为此添加一个方法Entity,有几种方法可以做到这一点

  1. 正如@Thomas Levesque在评论中所建议的,您可以使用SigninManager<ApplicationUser>.CreateUserPrincipalAsync()来做到这一点。

  2. 另一种方式是使用IUserClaimsPrincipalFactory<TUser>服务创建ClaimsPrincipal然后获取身份。

    var principal = _userClaimsPrincipalFactory.CreateAsync(TUser user);
    // ... now we have the principal.Claims 
    // ... now we have the principal.Identity 
    
    Run Code Online (Sandbox Code Playgroud)
  3. 最后,如果您只想生成ClaimsIdentity,则不需要UserManagerorSigninManagerUserClaimsPrincipalFactory<TUser>就像 ASP.NET Core 团队所做的那样简单地更新它:

公共类ApplicationUser:IdentityUser
{
    公共异步任务GenerateUserIdentityAsync(UserManager管理器)
    {
        var userIdentity = wait manager.CreateIdentityAsync(this,DefaultAuthenticationTypes.ApplicationCookie);
        var Identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);

        Identity.AddClaim(new Claim(ClaimTypes.Name, this.UserName));
        // ... 根据需要添加其他声明。

        返回身份;
    }

    // ...
}