欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

c# - Asp.net Core Identity - 操作步骤

程序员文章站 2022-03-09 10:44:54
...

1. Define a new class, derived from IdentityUser

public class AppUser : IdentityUser
    {
        public string DisplayName { get; set; }
    }

2. In your DataContext, change 
'public class DataContext : DbContext' 
to 
'public class DataContext : IdentityDbContext<AppUser>'

3. In your DataContext, method: 'protected override void OnModelCreating(ModelBuilder builder)' add code: 

base.OnModelCreating(builder);

4. Execute cmd:

dotnet ef migrations add "AddIdentity" -p Persistence -s API

5. In start project: "API" directory, execute cmd:

dotnet ef database update

7. In start project: "API" directory, add nuget package: 'Microsoft.AspNetCore.Identity.UI'

8. In start project: "API", method: 'public void ConfigureServices(IServiceCollection services)' add code below

// Add Identity Support
            var builder = services.AddIdentityCore<AppUser>();
            var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);
            identityBuilder.AddEntityFrameworkStores<DataContext>();
            identityBuilder.AddSignInManager<SignInManager<AppUser>>();

9. Add some seed data, using 'UserManager<AppUser> userManager':

 if (!userManager.Users.Any())
            {
                var users = new List<AppUser>
                {
                    new AppUser { DisplayName = "Bob", UserName = "bob", Email = "[email protected]" },
                    new AppUser { DisplayName = "Tom", UserName = "tom", Email = "[email protected]" },
                    new AppUser { DisplayName = "Jane", UserName = "jane", Email = "[email protected]" }
                };

                foreach(var user in users)
                {
                    await userManager.CreateAsync(user, "Pa$$w0rd");
                }
            }

 

相关标签: .NetCore