为什么WebMethod可以在没有EnableSessionState的情况下访问会话状态? [英] Why Can WebMethod Access Session State Without EnableSessionState?
问题描述
我在页面上有一个标记为[WebMethod]
的方法,该方法使用某些会话状态作为其操作的一部分.编写此代码后,突然出现了闪存,当您在[WebMethod]
中使用会话状态时,需要使用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?
后面的示例代码:
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"];
}
示例正文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>
推荐答案
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)]
因为您的页面可能扩展了System.Web.UI.Page,所以不必显式启用会话.在 http://msdn.microsoft.com/在en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx 中,您可以看到默认情况下已为Pages(您可能已经知道)启用了EnableSessionState.
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).
这篇关于为什么WebMethod可以在没有EnableSessionState的情况下访问会话状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!