asp.net – 为什么WebMethod访问会话状态没有EnableSessionState?

前端之家收集整理的这篇文章主要介绍了asp.net – 为什么WebMethod访问会话状态没有EnableSessionState?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在一个标记为[WebMethod]的页面上有一个方法,它使用一些会话状态作为其操作的一部分.在写了这段代码之后,当你在[WebMethod]中使用会话状态时,我突然有一个内存闪存,你需要使用EnableSessionState(例如参见这里: http://msdn.microsoft.com/en-us/library/byxd99hx.aspx).但似乎工作正常.为什么?

示例代码背后:

  1. protected void Page_Load(object sender,EventArgs args) {
  2. this.Session["variable"] = "hey there";
  3. }
  4. [System.Web.Services.WebMethod]
  5. public static string GetSessionVariable() {
  6. return (string)HttpContext.Current.Session["variable"];
  7. }

样品体html:

  1. <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
  2. <script type="text/javascript">
  3. function getSession() {
  4. $.ajax({
  5. type: 'POST',url: 'Default.aspx/GetSessionVariable',data: '{ }',contentType: 'application/json; charset=utf-8',dataType: 'json',success: function (msg) {
  6. document.getElementById("showSessionVariable").innerHTML = msg.d;
  7. }
  8. });
  9. return false;
  10. }
  11. </script>
  12. <form id="form1" runat="server">
  13. <div id="showSessionVariable"></div>
  14. <button onclick='return getSession()'>Get Session Variable</button>
  15. </form>

解决方法

http://msdn.microsoft.com/en-us/library/system.web.services.webmethodattribute.enablesession(v=vs.90).aspx,您会看到这适用于XML Web服务(即从System.Web.Services.WebService派生的类).
  1. [WebMethod(EnableSession=true)]

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

猜你在找的asp.Net相关文章