为什么WebMethod可以在没有EnableSessionState的情况下访问会话状态?

use*_*861 12 asp.net webforms session-state asmx webmethod

我在标记为a的页面上有一个方法,[WebMethod]它使用一些会话状态作为其操作的一部分.在我编写这段代码之后,EnableSessionState当你在a中使用会话状态时,我突然想要使用闪存[WebMethod](例如,请参阅此处:http://msdn.microsoft.com/en-us/library/byxd99hx.aspx) .但似乎工作正常.为什么?

示例代码背后:

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"];
}
Run Code Online (Sandbox Code Playgroud)

样本体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>
Run Code Online (Sandbox Code Playgroud)

Rya*_*n M 16

http://msdn.microsoft.com/en-us/library/system.web.services.webmethodattribute.enablesession(v=vs.90).aspx上,您将看到这适用于XML Web服务(即类)派生自System.Web.Services.WebService).

[WebMethod(EnableSession=true)]
Run Code Online (Sandbox Code Playgroud)

因为您的页面可能扩展了System.Web.UI.Page,所以没有必要显式启用会话.在http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx上,您可以看到默认情况下为Pages(您可能已经知道)启用了EnableSessionState.