【问题标题】:UserManager<XYZ>' does not contain a definition for 'CreateIdentityAsync' and no accessible extension methodUserManager<XYZ>' 不包含 'CreateIdentityAsync' 的定义,并且没有可访问的扩展方法
【发布时间】:2019-05-05 14:58:54
【问题描述】:

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

 var userIdentity = await manager.CreateIdentityAsync(this,DefaultAuthenticationTypes.ApplicationCookie);

我正在尝试从过去 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; }

    }

【问题讨论】:

  • CreateIdentityAsync 是一种 ASP.NET MVC 5 方法,它在 ASP.NET Core 中不存在。我认为SignInManager&lt;ApplicationUser&gt;.CreateUserPrincipalAsync 会做你想做的事。
  • 我想在我的 AspNetUser 表中添加一些属性。但我陷入了这个错误。
  • 我有同样的问题,将这个错误停留了 3 天 - “当前上下文中不存在名称 'DefaultAuthenticationTypes'”。请有人帮忙。

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


【解决方案1】:

不知道为什么需要在ApplicationUser 实体中生成ClaimsIdentity,它应该是POCO。据我所知,最好把它移到别的地方。

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

  1. 正如评论中@Thomas Levesque 所建议的,您可以使用SigninManager&lt;ApplicationUser&gt;.CreateUserPrincipalAsync() 来执行此操作。

  2. 另一种方法是使用IUserClaimsPrincipalFactory&lt;TUser&gt;服务创建ClaimsPrincipal,然后获取身份。

    var principal = _userClaimsPrincipalFactory.CreateAsync(TUser user);
    // ... now we have the principal.Claims 
    // ... now we have the principal.Identity 
    
  3. 最后,如果您只想生成ClaimsIdentity,则不需要UserManagerSigninManagerUserClaimsPrincipalFactory&lt;TUser&gt;。只需新建as the ASP.NET Core Team does:

公共类 ApplicationUser : IdentityUser { 公共异步任务 GenerateUserIdentityAsync(UserManager manager) { var userIdentity = await manager.CreateIdentityAsync(this,DefaultAuthenticationTypes.ApplicationCookie); 罢工> var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); identity.AddClaim(new Claim(ClaimTypes.Name, this.UserName)); // ... 根据需要添加其他声明。 返回身份; } // ... }

【讨论】:

  • 我试过了,但ApplicationUser.GenerateUserIdentityAsync 没有被击中。
猜你喜欢
  • 2023-01-19
  • 2020-10-06
  • 1970-01-01
  • 1970-01-01
  • 2020-06-14
  • 2022-07-21
  • 2023-01-12
  • 1970-01-01
  • 2019-12-04
相关资源
最近更新 更多