无法解析“ BackEnd.Models.UserContext”类型的服务

时间:2019-09-13 11:09:44

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

.NET Core应用程序是我的新手,我尝试使用angulare和.NET Core创建一个应用程序,但是当我想在应用程序中添加身份时,会遇到此错误:

  

处理请求时发生未处理的异常。   InvalidOperationException:无法解析类型的服务   尝试激活时出现“ BackEnd.Models.UserContext”   'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore 9[Microsoft.AspNetCore.Identity.IdentityUser,Microsoft.AspNetCore.Identity.IdentityRole,BackEnd.Models.UserContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim 1 [System.String],Microsoft.AspNetCore.Identity.IdentityUserRole 1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin 1 [System.String],Microsoft.AspNetCore.Identity.IdentityUserToken {{ 1}} 1 [System.String]]'。

这是我的代码:

1[System.String],Microsoft.AspNetCore.Identity.IdentityRoleClaim

启动

namespace BackEnd.Models
{
    public class UserContext: IdentityDbContext<IdentityUser>
    {
        public UserContext()
        {

        }

        public UserContext(DbContextOptions<UserContext> options): base(options)
        {

        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                IConfigurationRoot configuration = new ConfigurationBuilder()
                   .SetBasePath(Directory.GetCurrentDirectory())
                   .AddJsonFile("appsettings.json")
                   .Build();
                var connectionString = configuration.GetConnectionString("IdentityConnectionString");
                optionsBuilder.UseSqlServer(connectionString);
            }
        }

    }
}

1 个答案:

答案 0 :(得分:0)

您是否错过添加默认令牌提供者的机会? 像这样改变。

namespace BackEnd.Models
{
    // Add IdentityRole
    public class UserContext: IdentityDbContext<IdentityUser,IdentityRole>
    {
        public UserContext()
        {

        }
      ...
}

和此.AddDefaultTokenProviders();。失踪

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

       ...

        services.AddIdentity<IdentityUser, IdentityRole>()
                .AddEntityFrameworkStores<UserContext>()
                 // Here is missing
                .AddDefaultTokenProviders();;
    }

添加app.UseAuthentication();在cors之后

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseCors("EnableCORS");
        //add this
        app.UseAuthentication();
        app.UseMvc();
    }