【问题标题】:Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager' while attempting to activate 'WebShop.Controllers.User.UserController'尝试激活“WebShop.Controllers.User.UserController”时无法解析“Microsoft.AspNetCore.Identity.UserManager”类型的服务
【发布时间】:2019-11-16 03:42:15
【问题描述】:

我是实体框架的新手。 我正在开发一个 web 应用程序,我想为一个 Angular 站点创建一个用户身份验证模块。 用户登录完美。当我尝试添加用户角色时,我收到以下错误消息:

我收到以下错误: error

我使用 JWT 令牌作为身份验证器。 和 Microsoft.IdentityModel。

我的代码: 启动.cs 身份服务:

            services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<WebShopContext>();

JWT 自动服务:

 var key = Encoding.UTF8.GetBytes(Configuration["ApplicationSettings:JWT_Secret"]);

        services.AddAuthentication(x => 
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(x=> {
            x.RequireHttpsMetadata = false;
            x.SaveToken = false;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false,
                ClockSkew = TimeSpan.Zero 
            };
        });
    }

我的 ApplicationRole 模型:

public class ApplicationRole : IdentityRole
    {
        public ApplicationRole() : base() { }
        public ApplicationRole(string name) : base(name) { }
        public string Description { get; set; }
    }
}

我的 ApplicationUser 模型:

    public class ApplicationUser : IdentityUser
{
    [Column(TypeName="nvarchar(150)")]
    public string FullName { get; set; }

    [Column(TypeName = "nvarchar(100)")]
    public string FirstName { get; set; }

    [Column(TypeName = "nvarchar(100)")]
    public string LastName { get; set; }

}

我完全不知道。我怎么解决这个问题。请帮帮我。

【问题讨论】:

  • 您使用的是哪个版本的 .Net Core?
  • .Net core 2.2版 Entity framework core 2.2.4版

标签: c# entity-framework asp.net-core .net-core entity-framework-core


【解决方案1】:

尝试改变

            services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<WebShopContext>();

      services.AddIdentity<ApplicationUser, IdentityRole>() // <--- changed to ApplicationUser
      .AddEntityFrameworkStores<WebShopContext>();

我会假设,通过阅读错误,您从 IdentityUser 继承的模型是 ApplicationUser 并且您正在设置您的服务以查找 IdentityUser 而不是 ApplicationUser 这是你要什么。

【讨论】:

  • 是的,它的工作谢谢。但是现在我从数据库中读取了空数组,但是在数据库中有行。
  • 太好了,如果你能标记答案,我会喜欢的。
  • 另外,如果你得到一个空引用错误,也许你的数据库中没有任何东西?或者您在尝试查找用户时正在搜索错误的参数?只是一般要寻找的东西。
  • 我犯了一个愚蠢的错误 :D 现在一切正常。再次感谢您。
  • 在我的数据库中,数据行鉴别器值与 RoleManager 类的名称(“ApplicationRole”)不同,它不关心这些行。现在我将数据库中的鉴别器值更改为“ApplicationRole”,一切正常,我看到了每条记录。
猜你喜欢
  • 1970-01-01
  • 2021-08-07
  • 2022-01-04
  • 2019-05-20
  • 2018-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多