ASP.NET CORE 2.1身份已注册

时间:2018-08-01 08:52:07

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

我对Identity ASP.net Core 2.1有问题。我在startup.cs中创建角色。运行时显示错误

  

AggregateException:发生一个或多个错误。 (没有注册类型'Microsoft.AspNetCore.Identity.RoleManager`1 [Microsoft.AspNetCore.Identity.IdentityRole]的服务。)   System.Threading.Tasks.Task.Wait(int毫秒超时,CancellationToken cancelToken)   System.Threading.Tasks.Task.Wait()   Startup.cs中的ContosoUniversity.Startup.Configure(IApplicationBuilder应用程序,IHostingEnvironment env,IServiceProvider serviceProvider)   +               CreateRoles(serviceProvider).Wait();   Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder应用)   Microsoft.AspNetCore.Server.IISIntegration.IISSetupFilter + <> c__DisplayClass4_0.b__0(IApplicationBuilder应用)   Microsoft.AspNetCore.HostFilteringStartupFilter + <> c__DisplayClass0_0.b__0(IApplicationBuilder应用)   Microsoft.AspNetCore.Hosting.Internal.AutoRequestServicesStartupFilter + <> c__DisplayClass0_0.b__0(IApplicationBuilder构建器)   Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

Statup.cs文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using ContosoUniversity.Models;
using Microsoft.AspNetCore.Identity;
using ContosoUniversity.Areas.Identity.Data;

namespace ContosoUniversity
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

        }
        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddDbContext<SchoolContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("SchoolContext")));

            //services.AddIdentity<ContosoUniversityUser, IdentityRole>()
            //    .AddEntityFrameworkStores<IdentityContext>()
            //     .AddDefaultTokenProviders();


        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseMvc();
            CreateRoles(serviceProvider).Wait();
        }
        public async Task CreateRoles(IServiceProvider serviceProvider)
        {

            //adding custom roles
            var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            //serviceProvider.GetService<RoleManager<IdentityRole>>();
            var UserManager = serviceProvider.GetRequiredService<UserManager<ContosoUniversityUser>>();
            string[] roleNames = { "Admin", "Manager", "Member" };
            IdentityResult roleResult;
            foreach (var roleName in roleNames)
            {
                var roleExist = await RoleManager.RoleExistsAsync(roleName);
                if (!roleExist)
                {
                    roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
                }
            }
            var poweruser = new ContosoUniversityUser
            {
                UserName = Configuration.GetSection("UserSettings")["UserEmail"],
                Email = Configuration.GetSection("UserSettings")["UserEmail"]
            };

            string UserPassword = Configuration.GetSection("UserSettings")["UserPassword"];
            var _user = await UserManager.FindByEmailAsync(Configuration.GetSection("UserSettings")["UserEmail"]);

            if (_user == null)
            {
                var createPowerUser = await UserManager.CreateAsync(poweruser, UserPassword);
                if (createPowerUser.Succeeded)
                {
                    await UserManager.AddToRoleAsync(poweruser, "Admin");
                }
            }
        }
    }
}

3 个答案:

答案 0 :(得分:3)

您正尝试使用asp.net-identity而不在容器中注册它。

在configure-service方法中,取消注释这些行

services.AddIdentity<ContosoUniversityUser, IdentityRole>();
        .AddEntityFrameworkStores<IdentityContext>()
        .AddDefaultTokenProviders();

现在,服务提供商将了解这些服务,因为extension method为您注册了这些服务。

也不要忘记迁移数据库,以便它了解用户,角色等。

答案 1 :(得分:1)

我尝试在ConfigureServices中添加以下代码。这可以帮助我运行:

var builder = services.AddIdentityCore<ContosoUniversityUser>(opt =>
        {
            // Configure Password Options
            opt.Password.RequireDigit = true;
        }
        );
        builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
        builder.AddRoleValidator<RoleValidator<IdentityRole>>();
        builder.AddRoleManager<RoleManager<IdentityRole>>();
        builder.AddSignInManager<SignInManager<ContosoUniversityUser>>();
        builder.AddEntityFrameworkStores<IdentityContext>().AddDefaultTokenProviders();

        services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

答案 2 :(得分:0)

似乎您通过Identity实现了Asp.Net Core Identity Library

您可以检查您的项目以找到 ProjectName-> Areas-> Identity-> IdentityHostingStartup 。如下更改Configure

    public class IdentityHostingStartup : IHostingStartup
{
    public void Configure(IWebHostBuilder builder)
    {
        builder.ConfigureServices((context, services) => {
            services.AddDbContext<CoreAppContext>(options =>
                options.UseSqlServer(
                    context.Configuration.GetConnectionString("CoreAppContextConnection")));
            services.AddIdentity<ContosoUniversityUser, IdentityRole>()
                    .AddEntityFrameworkStores<CoreAppContext>();
        });
    }
}

更新

出于根本原因,是services.AddDefaultIdentity没有将IdentityRole添加到IServiceCollection,请检查此源代码IdentityServiceCollectionUIExtensions,它调用AddIdentityCore

尝试下面的代码。

public class IdentityHostingStartup : IHostingStartup
{
    public void Configure(IWebHostBuilder builder)
    {
        builder.ConfigureServices((context, services) => {
            services.AddDbContext<IdentityContext>(options =>
                options.UseSqlServer(
                    context.Configuration.GetConnectionString("IdentityContextConnection")));

            services.AddDefaultIdentity<ContosoUniversityUser>()
                    .AddRoles<IdentityRole>() // Add IdentityRole to ServiceCollection
                    .AddEntityFrameworkStores<IdentityContext>();
        });
    }
}