我正在使用visual studio 2015中的默认网站模板。我已经为用户添加了一些角色并分配了角色。当用户登录时,角色为零。我需要做些什么来使角色发挥作用?
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
var signInStatus = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
switch (signInStatus)
{
case SignInStatus.Success:
var user = await GetCurrentUserAsync();
return RedirectToLocal(returnUrl);
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid username or password.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
答案 0 :(得分:1)
查看您的代码,看起来您错过了对角色的任何检查。
我遇到了类似的问题,在深入研究代码之后,我注意到GetCurrentUserAsync()
没有返回有效的用户对象,而且返回null对象完好无损。 Context.User.GetUserId()
是问题,并且没有返回用户ID以传递给UserManager。
在解决此问题之前,我使用以下内容:
if (result.Succeeded)
{
var user = await UserManager.FindByEmailAsync(model.Email);
if (await UserManager.IsInRoleAsync(user, Roles.Admin))
{
return RedirectToAction("Index", "Admin");
}
return RedirectToLocal(returnUrl);
}
虽然这不太理想,但确实有效
答案 1 :(得分:0)
这对我有用...不会重定向正确无效的用户名或密码4我还会......会检查......
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewBag.ReturnUrl = returnUrl;
if (ModelState.IsValid)
{
var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
if (result.Succeeded)
{
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
这是针对MVC 6,(VS 2015 RC)......你可以在这里找到所有内容:https://github.com/aspnet/Identity/tree/dev/samples/IdentitySample.Mvc