[c#]需要注销成功使用 Ajax 之前清除 MySession 数据

标签: Asp.net ajax C#
发布时间: 2017/2/25 3:39:56
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

这是我第一次构建一个 web 应用程序。我想要使用 ajax 来访问 Default.aspx 到空 MySession Loggingout 功能。Ajax 调用会返回为成功而不是错误但尚未清除 MySession。

<script type="text/javascript">
        $(document).ready(function () {
            $("#Logout2").click(function (e) {
                alert(99);
                $.ajax({
                    type: 'POST',
                    url: 'Default.aspx/Loggingout',
                    data: '{a}',
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function (msg) {
                        window.location = '<%=this.ResolveClientUrl("~/Default.aspx")%>';
                },
                    error: function (e) {
                        alert(0);
                    }
                });
                e.preventDefault();
            });
        });
    </script>

我把测试警报和它不去错误的一面,这是 alert(0)。它已成功地返回到默认页清除 MySession。我试过破发点放 Loggingout 函数,但它并不在该函数中运行。

<script type="text/C#" runat="server">
[WebMethod]
public static string Loggingout(string a)
{
    CarPark.MySession.Current.UserID = Guid.Empty;
    CarPark.MySession.Current.Username = "";
    CarPark.MySession.Current.UserEmail = "";
    CarPark.MySession.Current.UserRole = "";
    return "done";
}

这是写在 Default.aspx 页面的功能。

public class MySession
{
    // private constructor
    private MySession()
    {
        UserID = Guid.Empty;
        Username = "";
        UserEmail = "";
        UserRole = "";
    }
    // Gets the current session.
    public static MySession Current
    {
        get
        {
            MySession session =
              (MySession)HttpContext.Current.Session["__MySession__"];
            if (session == null)
            {
                session = new MySession();
                HttpContext.Current.Session["__MySession__"] = session;
            }
            return session;
        }
    }
    public Guid UserID { get; set; }
    public string Username { get; set; }
    public string UserEmail { get; set; }
    public string UserRole { get; set; }
}

如果您想要查看 MySession

解决方法 1:

[WebMethod]
public static string Loggingout(string a)
{
    // if you use FormsAuthentication call this.
    FormsAuthentication.SignOut();

    // You can clear your session....
    HttpContext.Current.Session.Clear();

    // ... or just set your session to a new object.
    HttpContext.Current.Session["__MySession__"] = new MySession();

    return "done";
}
官方微信
官方QQ群
31647020