问题描述
我在页面上有一个标记为 [WebMethod]
的方法,它使用一些会话状态作为其操作的一部分.在我写完这段代码后,我突然有一个记忆,当你在 [WebMethod]
中使用会话状态时,你需要使用 EnableSessionState
(例如,参见这里:http://msdn.microsoft.com/en-us/library/byxd99hx.aspx一>).但它似乎工作正常.为什么?
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,您将看到这适用于 XML Web services(即从 System.Web.Services.WebService 派生的类).
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,你可以看到页面默认启用了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 的情况下访问会话状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!