asp.net - 使用 Windows 身份验证注销 ASP.NET MVC 应用程序并能够使用同一用户再次登录

标签 asp.net asp.net-mvc windows-authentication logout

我正在使用 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/

相关文章:

ASP.Net循环引用情况

c# - 在不使用回发的情况下调用 Web 服务

c# - response.redirect 和 server.transfer 的区别

javascript - 脚本运行失控

c# - 即使在输入有效凭据后,Windows 身份验证弹出窗口仍会继续出现

c# - 如何将 Windows 身份验证凭据从客户端传递到 Web API 服务

jquery - 将 JQUERY 操作的 HTML 表数据保存到 ASP.NET 中(最好是 session )

asp.net - 无效操作。连接已关闭。 ASP.NET MVC

asp.net - 在 ASP.NET MVC( View )中包含 WebForms?

c# - Windows 身份验证在部署 MVC 站点时不起作用