我有一个名为Auth的mvc控制器,以及一个名为login的操作,看起来像这样..
[HttpPost]
public async Task<ActionResult> LogIn(LogInModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var user = await userManager.FindAsync(model.Email, model.Password);
if (user != null)
{
await SignIn(user);
if (!string.IsNullOrWhiteSpace(model.ReturnUrl))
{
return Redirect(GetRedirectUrl(model.ReturnUrl));
}
else
{
//return RedirectToAction("Index", "Home");
return Redirect("../Home/Index");
}
}
else
{
return View();
}
// user authN failed
//ModelState.AddModelError("", "Invalid email or password");
//return View();
}
但是我没有重定向到我的../Home/Index。即使我成功登录,我也会待在同一页面上。这可能有什么问题?
答案 0 :(得分:0)
您使用的是什么版本的MVC?我使用以下方法保护过去使用登录的页面,并检查属于asp.net Identitiy的枚举,因为您可以看到返回URL被传递给方法。
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
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.Username, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
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);
}
}
如果您使用的是MVC 4,则可以使用[AllowAnonymous]
答案 1 :(得分:0)
在方法调用更改为Ajax之后,出现了相同的问题。只需将响应类型更改为JavaScript并要求其执行导航,因为调用结果是在Javscript代码块内处理的
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
var returnUrlJs = string.Format("location.href='{0}'", returnUrl);
return new JavaScriptResult() { Script = returnUrlJs };