您可以在控制台应用程序中集成身份并将用户添加到数据库中,请按照以下步骤操作:
1.添加以下包:
<PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.2.0" />
2.创建Models目录并创建ApplicationUser和ApplicationDbContext
public class ApplicationUser : IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
3。添加一个实现IDesignTimeDbContextFactory的类
public class ApplicationDbContextFactory:IDesignTimeDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=ConsoleAppIdentity;Trusted_Connection=True;ConnectRetryCount=0");
return new ApplicationDbContext(optionsBuilder.Options);
}
}
4.添加并执行合并
PM> add-migration CreateInitial
PM> update-database
5.Program.cs的代码
class Program
{
static void Main(string[] args)
{
var services = new ServiceCollection();
//setup our DI
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options=> {
options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=ConsoleAppIdentity;Trusted_Connection=True;ConnectRetryCount=0");
});
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddScoped<IUserCreationService, UserCreationService>();
// Build the IoC from the service collection
var provider = services.BuildServiceProvider();
var userService = provider.GetService<IUserCreationService>();
userService.CreateUser().GetAwaiter().GetResult();
Console.ReadKey();
}
public interface IUserCreationService
{
Task CreateUser();
}
public class UserCreationService : IUserCreationService
{
public readonly UserManager<ApplicationUser> userManager;
public UserCreationService(UserManager<ApplicationUser> userManager)
{
this.userManager = userManager;
}
public async Task CreateUser()
{
var user = new ApplicationUser { UserName = "TestUser", Email = "test@example.com" };
var result = await this.userManager.CreateAsync(user, "Test@123");
if (result.Succeeded == false)
{
foreach (var error in result.Errors)
{
Console.WriteLine(error.Description);
}
}
else
{
Console.WriteLine("Done.");
}
}
}
}