将身份验证移至服务层

时间:2016-03-20 13:11:50

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

我正在尝试将asp.net身份3身份验证从控制器转移到服务,n层架构,这将管理用户身份验证。首先,我想知道将身份验证从控制器移动到服务层是否是个好主意。 一切顺利,直到我尝试使用UserManager.CreateAsync()方法,方法停止工作并重定向到相同的寄存器页面。 这是我的帐户服务代码:

namespace CVProject.Services.Account
{
    public class AccountService : IAccountService
    {
        private ApplicationDbContext _DbContext;
        private readonly UserManager<User> _userManager;
        private readonly SignInManager<User> _signInManager;
        private readonly RoleManager<UserRole> _roleManager;

        public AccountService(ApplicationDbContext DbContext,
            UserManager<User> userManager,
            SignInManager<User> signInManager,
            RoleManager<UserRole> roleManager)
        {
            _DbContext = DbContext;
            _userManager = userManager;
            _signInManager = signInManager;
            _roleManager = roleManager;
        }


        public async Task<IdentityResult> CreateEmployeeAccount(EmployeeRegisterViewModel model)
        {
            var user = new User { UserName = model.Username, Email = model.Email, Name = (model.FirstName + model.LastName)};
            var result = await _userManager.CreateAsync(user, model.Password);
            if(result.Succeeded)
            {
                if(!await _roleManager.RoleExistsAsync(model.Role))
                {
                    await _roleManager.CreateAsync(new UserRole(model.Role));
                }
                await _userManager.AddToRoleAsync(user,model.Role);
                await _signInManager.SignInAsync(user, isPersistent: false);
            }
            return result;
        }

    }
}

我的控制器代码:

    [HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> Register(EmployeeRegisterViewModel employeeRegisterModel)
    {
        if (ModelState.IsValid)
        {
            IdentityResult result = await _service.CreateEmployeeAccount(employeeRegisterModel);
            if (result.Succeeded)
            {
                return RedirectToAction(nameof(EmployeeController.Index), "Home");
            }
            AddErrors(result);
        }

        return View(employeeRegisterModel);
    }

以及可能影响此代码的startup.cs代码:

 services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration["Data:DbContextConnection"]));


        services.AddIdentity<User, UserRole>(config => 
            {
                config.User.RequireUniqueEmail = true;
                config.Password.RequiredLength = 8;
                config.Cookies.ApplicationCookie.LoginPath = "/Employee/Login";
            })
        .AddEntityFrameworkStores<ApplicationDbContext,string>()
        .AddDefaultTokenProviders();

        services.AddTransient<IAccountService, AccountService>();

由于

1 个答案:

答案 0 :(得分:0)

您正尝试在登录用户时与执行请求的用户登录。您可能在那里遇到了一些问题。

删除此代码await _signInManager.SignInAsync(user, isPersistent: false);