我在一个标记为[WebMethod]的页面上有一个方法,它使用一些会话状态作为其操作的一部分.在写了这段代码之后,当你在[WebMethod]中使用会话状态时,我突然有一个内存闪存,你需要使用EnableSessionState(例如参见这里:
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"];
- }
样品体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>
解决方法
在
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)]
因为你的页面大概扩展了System.Web.UI.Page,所以没有必要明确地启用会话.在http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx,您可以看到,默认情况下,页面启用了EnableSessionState(您可能已经知道).