我正在使用 Windows 身份验证在 ASP.NET MVC 中构建应用程序。 我需要一种方法来注销已登录的用户,以便新用户可以登录到同一应用程序而无需关闭浏览器。 为此,我找到了一个巧妙的解决方案,如下所示:
public ActionResult LogOut()
{
HttpCookie cookie = Request.Cookies["TSWA-Last-User"];
if(User.Identity.IsAuthenticated == false || cookie == null || StringComparer.OrdinalIgnoreCase.Equals(User.Identity.Name, cookie.Value))
{
string name = string.Empty;
if(Request.IsAuthenticated)
{
name = User.Identity.Name;
}
cookie = new HttpCookie("TSWA-Last-User", name);
Response.Cookies.Set(cookie);
Response.AppendHeader("Connection", "close");
Response.StatusCode = 0x191;
Response.Clear();
//should probably do a redirect here to the unauthorized/failed login page
//if you know how to do this, please tap it on the comments below
Response.Write("Unauthorized. Reload the page to try again...");
Response.End();
return RedirectToAction("Index");
}
cookie = new HttpCookie("TSWA-Last-User", string.Empty)
{
Expires = DateTime.Now.AddYears(-5)
};
Response.Cookies.Set(cookie);
return RedirectToAction("Index");
}
然而,这种方法的问题是同一用户无法再次登录。它始终需要是与当前用户不同的用户。
我想我应该能够通过更改 if 子句来做到这一点。 我也尝试删除 StringComparer.OrdinalIgnoreCase.Equals(User.Identity.Name, cookie.Value) 条件,但它无法工作,因为 cookie 值可能不为空。
最佳答案
请检查此帖子!它对我有用!
https://stackoverflow.com/a/3889441
以防万一,我将代码粘贴到此处:
@Palantir 说:
That's strange... I make one single call to: FormsAuthentication.SignOut(); and it works...
public ActionResult Logout() {
FormsAuthentication.SignOut();
return Redirect("~/");
}
关于asp.net - 使用 Windows 身份验证注销 ASP.NET MVC 应用程序并能够使用同一用户再次登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27821127/