我正在使用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值不为null,因此无法正常工作 .
1 回答
请查看这篇文章!它对我有用!
https://stackoverflow.com/a/3889441
为了以防万一,我在这里粘贴代码:
@Palantir说: