Core应用程序中创建用户

Core应用程序中创建用户

本文介绍了在控制台.NET Core应用程序中创建用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含3个项目(Web,控制台应用程序,DataAccessLayer)的ASP.NET Core 1.0解决方案.我使用ASP.NET Core身份和Entity Framework Core(SQL Server-代码优先).

I have a ASP.NET Core 1.0 Solution with 3 projects (Web, Console Application, DataAccessLayer).I use ASP.NET Core Identity and Entity Framework Core (SQL Server - Code First).

我想在控制台应用程序(用于后台任务)中创建用户,但是如何在控制台应用程序(或.NET Core类库)中访问UserManager对象?

In my Console Application (Used for background tasks), I want to create users, but how I can have access to UserManager object in a Console Application (Or in a .NET Core Class Library) ?

在控制器类中,使用依赖注入很容易:

In a controller class, it's easy with Dependency Injection :

public class AccountController : Controller  {
private readonly UserManager<ApplicationUser> _userManager;

public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
    _userManager = userManager;
}

//...

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
    var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
    var result = await _userManager.CreateAsync(user, model.Password);

    //...
}

如何在Console Core Application中完成等效的工作?

How I can do the equivalent in a Console Core Application ?

推荐答案

感谢Tseng的回答,我最终获得了这段代码.以防万一有人需要:

Thanks to Tseng's answer I ended up with this code. Just in case if someone would need:

public class Program
    {
        private interface IUserCreationService
        {
            Task CreateUser();
        }

        public static void Main(string[] args)
        {
            var services = new ServiceCollection();

            services.AddDbContext<ApplicationDbContext>(
            options =>
            {
                options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=my-app-db;Trusted_Connection=True;MultipleActiveResultSets=true");
            });

            // Authentification
            services.AddIdentity<ApplicationUser, IdentityRole>(opt =>
            {
                // Configure identity options
                opt.Password.RequireDigit = false;
                opt.Password.RequireLowercase = false;
                opt.Password.RequireUppercase = false;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequiredLength = 6;
                opt.User.RequireUniqueEmail = true;
            })
                .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();
        }

        private class UserCreationService : IUserCreationService
        {
            private readonly UserManager<ApplicationUser> userManager;

            public UserCreationService(UserManager<ApplicationUser> userManager)
            {
                this.userManager = userManager;
            }

            public async Task CreateUser()
            {
                var user = new ApplicationUser { UserName = "TestUser", Email = "[email protected]" };
                var result = await this.userManager.CreateAsync(user, "123456");

                if (result.Succeeded == false)
                {
                    foreach (var error in result.Errors)
                    {
                        Console.WriteLine(error.Description);
                    }
                }
                else
                {
                    Console.WriteLine("Done.");
                }
            }
        }
    }

这篇关于在控制台.NET Core应用程序中创建用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 14:04