Why is WebMethod Access Session State without EnableSessionState?

I have a method on a page marked as [WebMethod] that uses some session state as part of its operation. After I wrote this code, I suddenly had a flash of memory that you need to use EnableSessionState when you use the session state in [WebMethod] (for example, see here: http://msdn.microsoft.com/en- us / library / byxd99hx.aspx ). But it seems to be working fine. Why?

Code example:

 protected void Page_Load(object sender, EventArgs args) { this.Session["variable"] = "hey there"; } [System.Web.Services.WebMethod] public static string GetSessionVariable() { return (string)HttpContext.Current.Session["variable"]; } 

Body html example:

 <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript"> function getSession() { $.ajax({ type: 'POST', url: 'Default.aspx/GetSessionVariable', data: '{ }', contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (msg) { document.getElementById("showSessionVariable").innerHTML = msg.d; } }); return false; } </script> <form id="form1" runat="server"> <div id="showSessionVariable"></div> <button onclick='return getSession()'>Get Session Variable</button> </form> 
+12
webforms asmx session-state webmethod
Mar 22 '13 at 13:39
source share
2 answers

At http://msdn.microsoft.com/en-us/library/system.web.services.webmethodattribute.enablesession(v=vs.90).aspx you will see that this applies to XML web services (i.e. to classes derived from System.Web.Services.WebService).

 [WebMethod(EnableSession=true)] 

Since your page seems to extend System.Web.UI.Page, there is no need to explicitly enable the session. At http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx you can see that EnableSessionState is enabled by default for Pages (which you probably already know).

+15
Mar 29 '13 at 21:34
source share

http://forums.asp.net/t/1630792.aspx/1

Gsndotnet's answer to this question: You are correct, but everything you say applies to the method in the context of WebServices. We also use the same WebMethod attribute for WebService (.asmx) methods. Therefore, in the context of web services, when we want to allow access to a session, we must add EnableSession = true. If in the context of PageMethods they already have access to the session, because they are defined inside a class that inherits from the Page class.

Your msdn link means you are using a web service, i.e. a class derived from System.Web.Services.WebService. In the code, you add your method directly to the page, so it has access to the session.

+3
Mar 29 '13 at 21:26
source share



All Articles