首页 > 解决方案 > Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager' while attempting to activate 'WebShop.Controllers.User.UserController'

问题描述

Im new at Entity-framework. And im working on a webapplication, I want to make a userauthentication modul to an Angular site. User login work perfectly.When i try to add user roles i got the following error message:

And I got the following error: error

I using JWT token for authenticator. And Microsoft.IdentityModel.

My code: Startup.cs Identity service:

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

JWT aut service:

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

My ApplicationRole model:

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

My ApplicationUser model:

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

}

I have absolutly no idea. How can I solve this problem. Please help me.

标签: c#entity-frameworkasp.net-core.net-coreentity-framework-core

解决方案


尝试改变

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

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

我将假设,通过阅读错误,您的模型继承自IdentityUserisApplicationUser并且您正在设置您的服务来寻找IdentityUser而不是ApplicationUser您所要求的。


推荐阅读