Why Can WebMethod Access Session State Without EnableSessionState?
Asked Answered
R

2

13

I have a method on a page marked as a [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 session state in a [WebMethod] (e.g. see here: http://msdn.microsoft.com/en-us/library/byxd99hx.aspx). But it seems to be working fine. Why?

Sample code behind:

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

Sample body html:

<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>
Randalrandall answered 22/3, 2013 at 13:39 Comment(0)
K
17

On 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., classes derived from System.Web.Services.WebService).

[WebMethod(EnableSession=true)]

Because your page presumably extends System.Web.UI.Page, it is not necessary to explicitly enable the session. On 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).

Kisner answered 29/3, 2013 at 21:34 Comment(0)
T
3

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

Answer of gsndotnet: You are right but whatever you are saying is applicable to a method in context of WebServices. We also use same WebMethod attribute on the methods of a WebService (.asmx). So in context of Web Services when we want to allow the access to Session we have to add EnableSession = true. Whereas in context of PageMethods they already have access to Session as they are defined inside a class that inherits from Page class.

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

Thilda answered 29/3, 2013 at 21:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.