morzel.net

.net, js, html, arduino, java... no rants or clickbaits.

Session access from Page Methods

ASP.NET AJAX offers easy to use and effective mechanism to invoke methods on the server from JavaScript. It’s called Page Methods. Because those methods are static* you cannot use Page.Session property.  This does not mean that you have to give up the use of the session. Simply, you should use the HttpContext.Current.Session instead of Page.Session.

For instance, to save and read a value from session state, just use the code:

[WebMethod]
public static void SaveToSession(string s)
{
    HttpContext.Current.Session["abc"] = s;
}

[WebMethod]
public static string ReadFromSession()
{
    return (string)HttpContext.Current.Session["abc"];
}

And what if you want to get a logged user name? It is equally simple, use: HttpContext.Current.User.Identity.Name.

Access to session’s data is possible because when you send requests via the XmlHttpRequest object, the session ID cookie is also included. This cookie looks like this:

Cookie: ASP.NET_SessionId=kxxrwp45bhkyyhbzpijo0zj4

* Page Methods are static - and they should be! In this way, Page object creation is avoided and ViewState is not transmitted. The server has less work (no events such as Page_Load or Page_PreRender occur) and the amount of data sent over the network is significantly smaller.