How can I clear asp.net session value in OnUnload

2019-08-05 13:03发布

I'd like to clear ASP.NET session value when browser closed. I've onunload function defined in my html page, but I don't know how can I clear session value in this Javascript method ?

<body onunload="myUnloadFunction()">


<script>
function myUnloadFunction()
{
  // Needs asp.net session code here
}
</script>

Please let me know Is it possible else any other preferable way of doing.

1条回答
唯我独甜
2楼-- · 2019-08-05 13:28

Try this:

Code-behind:

[WebMethod]
public static void ClearYourSessionValue()
{
    // This will leave the key in the Session cache, but clear the value
    Session["YourKey"] = null;

    // This will remove both the key and value from the Session cache
    Session.Remove("YourKey");
}

JavaScript:

$.ajax({
    type: "POST",
    url: "PageName.aspx/ClearYourSessionValue",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
         // Do something interesting here.
    }
});

If you want more information about ASP.NET AJAX Page Methods and how to invoke them via AJAX then read Using jQuery to directly call ASP.NET AJAX page methods

查看更多
登录 后发表回答