问题描述
我正在使用ASP.NET MVC生成的默认Login方法,并希望对其进行更改,以便它将根据用户角色重定向到指定的View.我已经检查过该用户是否在该角色中.我在SignInStatus成功块内进行了重定向,但未成功.
I am using the default Login method generated by ASP.NET MVC and wanted to change it so that it will redirect to a specified View based on the user's role. I have checked that the user is in that role. I made the redirect inside the SignInStatus success block with no success.
我在其他代码块中使用 User.IsInRole()
,并且工作正常.我认为执行if语句时用户尚未完全登录.我认为是这种情况,但是我不确定我可以实施哪些解决方案.
I use the User.IsInRole()
in other blocks of code and works fine. I think the user is not fully logged in when the if statements are executed. I think this is the case, but I am not sure what work around I can implement.
这是我的下面的代码.
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateCustomAntiForgeryTokenAttribute]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
if (User.IsInRole("Customer"))
{
return RedirectToAction("Customer", "Home");
}
else if (User.IsInRole("Requestor"))
{
return RedirectToAction("Caterer", "Home");
}
else if (User.IsInRole("Admin"))
{
return RedirectToAction("Admin", "Home");
}
else
{
return RedirectToLocal(returnUrl);
}
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
推荐答案
感谢@ stephen.vakil的链接,我通过更改SignInStatus.Success案例中的代码块使它能够正常工作.
Thanks to @stephen.vakil's link I managed to get it to work by changing the block of code inside the SignInStatus.Success case.
case SignInStatus.Success:
var user = await UserManager.FindAsync(model.Email, model.Password);
var roles = await UserManager.GetRolesAsync(user.Id);
if (roles.Contains("Customer"))
{
return RedirectToAction("Customer", "Home");
}
else if (roles.Contains("Requestor"))
{
return RedirectToAction("Caterer", "Home");
}
else if (roles.Contains("Admin"))
{
return RedirectToAction("Admin", "Home");
}
else
{
return RedirectToLocal(returnUrl);
}
......
这篇关于基于角色的ASP.NET MVC登录和重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!