如何在 ASP.NET 核心 2.2 中实现标识

在我的网站中,我想让管理员使用帐户登录以修改数据库。此外,我可能会在将来添加一些角色和帐户。


因此,我正在尝试实现标识。


我在Visual Studio 2019中做了一个项目(不确定这是否重要),并使用MVC选择了 ASP.NET Core 2.2(我自己安装了Core 2.2),使用个人用户帐户进行身份验证,我点击了显示:“配置HTTPS”的框。


完成项目后,我打开它,创建一个随机帐户,得到一个错误,然后迁移数据库以修复它。


然后,我添加:appsetting.json


"UserSettings": {

    "UserName": "MyAdminUser",

    "UserEmail": "MyAdminUser@gmail.com",

    "UserPassword": "A_123456a"

}

在文件夹内创建一个新类:Data


using System;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Identity;

using Microsoft.Extensions.Configuration;

using Microsoft.Extensions.DependencyInjection;


namespace WebApplication1.Data {

    public static class Seed {

        public static async Task CreateRoles(IServiceProvider serviceProvider, IConfiguration Configuration) {

            // Add customs roles

            var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();

            // Note: I used IdentityUser instead of make my ApplicationUser as other people do because the default idendity is fine for me, I don't need additional fields nor I want to make this more difficult.

            var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();

            string[] roleNames = { "Admin" };

            IdentityResult roleResult;


            foreach (var roleName in roleNames) {

                // Create roles and seeding them to the database

                var roleExist = await RoleManager.RoleExistsAsync(roleName);

                if (!roleExist) {

                    roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));

                }

            }


            // Create a super user

            var poweruser = new IdentityUser {

                UserName = Configuration.GetSection("AppSettings")["UserSettings:UserName"],

                Email = Configuration.GetSection("AppSettings")["UserSettings:UserEmail"]

            };

}


慕后森
浏览 105回答 2
2回答

呼如林

问题是,您尝试在不创建作用域的情况下从中检索作用域服务。有趣的是,您在对 的调用周围创建了一个作用域,但随后传入 了 未限定作用域。IServiceProviderSeed.CreateRolesIServiceProvider您应该做的是传入并在方法中创建作用域,或者将作用域创建保留在现在的位置,而是传入作用域服务,即 和。IServiceProviderSeed.CreateRolesRoleManagerUserManager编辑您需要执行下列操作之一:注入,然后在种子方法中创建您的范围:IServiceProvidervar host = CreateWebHostBuilder(args).Build();Seed.CreateRoles(host.Services);host.Run();然后:public static async Task CreateRoles(IServiceProvider services) {&nbsp; &nbsp; var configuration = services.GetRequiredService<IConfiguration>();&nbsp; &nbsp; using (var scope = services.CreateScope())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();&nbsp; &nbsp; &nbsp; &nbsp; var userManager = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();&nbsp; &nbsp; &nbsp; &nbsp; // seed data&nbsp; &nbsp; }}注入您的作用域服务:var host = CreateWebHostBuilder(args).Build();var configuration = host.Services.GetRequiredService<IConfiguration>();using (var scope = host.Services.CreateScope()){&nbsp; &nbsp; var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();&nbsp; &nbsp; var userManager = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();&nbsp; &nbsp; Seed.CreateRoles(configuration, roleManager, userManager);}host.Run();

一只萌萌小番薯

运行代码会在以下行中显示异常:var&nbsp;RoleManager&nbsp;=&nbsp;serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();根据异常,您似乎缺少文件中的配置来启用标识。我看不到你的,但我怀疑你错过了整个电话。startup.csstartup.csservices.AddIdentity(...)我建议您花一些时间阅读如何在 ASP.NET 核心中配置标识。Microsoft Docs&nbsp;始终是一个很好的起点。此外,您在问题中提到的第二个问题有很好的步骤。您特别需要查看步骤 2 和步骤 3。
打开App,查看更多内容
随时随地看视频慕课网APP