在使用Ajax成功注销之前需要清除MySession数据

时间:2017-01-06 15:12:03

标签: c# asp.net ajax webforms

这是我第一次构建Web应用程序。我想使用ajax访问Default.aspx中的Loggingout函数来清空MySession。 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>

我已对测试发出警报,但它没有进入警报(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

2 个答案:

答案 0 :(得分:0)

[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";
}

答案 1 :(得分:0)

Session.Abandon() Method

Abandon方法销毁存储在Session对象中的所有对象并释放其资源。如果未明确调用Abandon方法,则会话超时时服务器会销毁这些对象。

参考: - https://msdn.microsoft.com/en-us/library/ms524310(v=vs.90).aspx