我在这里有这些代码用于登录POST和GET
[Authorize]
public class AccountController : Controller
{
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return RedirectToLocal(returnUrl);
}
if (User.IsInRole("Owner"))
{
return RedirectToAction("Index", "AdminOnly");
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
然而,我的问题是,当我尝试登录管理员帐户时,我会重定向到〜/ Shared / Layout。我该怎么办?提前谢谢!
答案 0 :(得分:0)
如果有效,您的第一个if
语句会立即重定向用户。由于您已退出该方法,因此您永远无法检查其角色。在重定向之前更改方法以测试用户角色
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
if (User.IsInRole("Owner"))
{
return RedirectToAction("Index", "AdminOnly");
}
else
{
return RedirectToLocal(returnUrl);
}
}
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
答案 1 :(得分:-1)
我在同一个论坛上阅读了@KurtSchindler的回答。此代码块的工作方式类似于魅力
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
string[] roles = Roles.GetRolesForUser(model.UserName);
if (roles.Contains("Owner") || roles.Contains("Superuser"))
{
return RedirectToAction("Index", "AdminOnly");
}
else
{
return RedirectToAction("Index", "Home");
}
}
现在将我重定向到AdminOnly控制器内的Index。希望这可以帮助!谢谢!