2015-10-18 80 views
0

我正在構建一個嚴重仿照教程here的應用程序。它實質上是一個在線商店應用程序,當用戶到達網站時,它會分配一個唯一的字符串ID,用於存儲用戶在數據庫中選擇的內容。該字符串標識用戶購物車。HttpContext空錯誤

我有一些使用D3.js的客戶端JavaScript需要將一些信息發送回服務器。我添加了一個Web服務(.asmx),它很好地用於接收數據,但在接收到數據後,服務器會在數據庫中查找用戶的信息,但無法重新生成唯一的Id。

該教程給了我一個函數,該函數返回字符串Id,並在JavaScript調用asmx函數之前運行良好。我無法弄清楚爲什麼只有在Web服務運行後纔會出現此錯誤。

它獲取該ID的功能

public string GetVirusId() 
    { 
     //Line where I get the error 
     if (HttpContext.Current.Session[DescriptionSessionKey] == null) 
     { 
      if (!string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name)) 
      { 
       HttpContext.Current.Session[DescriptionSessionKey] = HttpContext.Current.User.Identity.Name; 
      } 
      else 
      { 
       // Generate a new random GUID using System.Guid class.  
       Guid tempDescriptionId = Guid.NewGuid(); 
       HttpContext.Current.Session[DescriptionSessionKey] = tempDescriptionId.ToString(); 
      } 
     } 
     return HttpContext.Current.Session[DescriptionSessionKey].ToString(); 
    } 

我得到的錯誤是:

Message: "Object reference not set to an instance of an object." 

我ASMX Web服務文件

namespace Trojan 
{ 
    /// <summary> 
    /// Summary description for updateGraph 
    /// </summary> 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService] 
    public class updateGraph : System.Web.Services.WebService 
    { 

     [WebMethod] 
     public bool analyseGraph(int x) 
     { 
      bool B = true; 
      using (VirusDescription virus = new VirusDescription()) 
      { 
       B = virus.updateGraph(x); 
      } 
      return B; 
     } 
    } 
} 
+1

如果你正在學習ASP.NET,它可能是一個好主意,學習的Web API,而不是的ASMX,因爲那些不再被微軟支持。另外,當你遇到錯誤時,你應該說明哪一行是由它引起的。如果它是一個NullReferenceException,你應該聲明哪個對象爲null。您的標題聽起來像HttpContext爲空。 – mason

回答

0

我想通了。顯然,對於Web方法,會話支持默認關閉。你可以閱讀更多關於它here.

我改變了我的Web服務方法下面,現在工作得很好:

namespace Trojan 
{ 
    /// <summary> 
    /// Summary description for updateGraph 
    /// </summary> 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService] 
    public class updateGraph : System.Web.Services.WebService 
    { 

     [WebMethod(EnableSession = true)] 
     public bool analyseGraph(int x) 
     { 
      bool B = true; 
      using (VirusDescription virus = new VirusDescription()) 
      { 
       B = virus.updateGraph(x); 
      } 
      return B; 
     } 
    } 
}