Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Can WebMethod Access Session State Without EnableSessionState?

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>
like image 647
user12861 Avatar asked Mar 22 '13 13:03

user12861


2 Answers

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).

like image 124
Ryan M Avatar answered Oct 23 '22 17:10

Ryan M


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.

like image 44
Vladimir Avatar answered Oct 23 '22 17:10

Vladimir