文章編號: 816637 - 上次校閱: 2007年5月16日 - 版次: 2.4

如何: 使用 CookieContainer 來維護 Web 服務中的狀態,當您使用 Visual C#.NET

系統提示本文適用於您使用的作業系統之外的作業系統。與您不相關的文章內容已停用。

在此頁中

全部展開 | 全部摺疊

結論

本文將逐步告訴您,如何使用 System.Net.CookieContainer 類別,當您為 Web 服務應用程式中使用工作階段或 Cookie 時。

雖然 Web 服務原本就是沒有狀態 (Stateless),您可以使用工作階段物件,為維護用戶端應用程式和伺服器應用程式之間的可設定狀態通訊。若要以便 Web 用戶端與 Web 服務之間的狀態式通訊中,您可以使用 CookieContainer 物件以從用戶端應用程式傳送到 Web 服務每個訊息。您可能會耗用在啟用狀態的用戶端應用程式中可設定狀態的 Web 服務。



建立 Web 服務應用程式

  1. 執行 Microsoft Visual Studio.NET。建立新的 ASP.NET Web 服務藉由使用 Visual C#.NET 的專案。

    根據預設值,Service1.asmx,即建立。
  2. 為專案的名稱 WebService1
  3. 在 [建置] 功能表上按一下 建置方案


啟用伺服器上的工作階段支援

預設情況下,ASP.NET 工作階段支援,為每個 Web 服務方法被關閉的。您必須明確啟用需要工作階段狀態的每個 Web 服務方法的工作階段支援。若要以便工作階段支援 EnableSession 屬性加入 WebMethod 屬性。要這麼做,請您執行下列步驟:
  1. 在 [方案總管] 中 Service1.asmx 上按一下滑鼠右鍵],並再以下列程式碼取代現有的程式碼:
    using System;
    using System.ComponentModel;
    using System.Web;
    using System.Web.Services;
    
    namespace WebService1
    {
    	/// <summary>
    	/// Summary description for Service1.
    	/// </summary>
    	public class Service1 : System.Web.Services.WebService
    	{
    		public Service1()
    		{
    			//CODEGEN:  Call required by ASP.NET Web Services Designer.
    			InitializeComponent();
    		}
    
    		#region Component Designer generated code
    	
    		private void InitializeComponent()
    		{
    		}
    
    		
    		#endregion
    
          [WebMethod(EnableSession=true)]
          public string SetTime(string CurrentTime)
          {
             Session.Add("Time", CurrentTime);
             return ((string) Session["Time"] );			
          }	
    
          [WebMethod(EnableSession=true)]
          public string GetTime()
          {
             return ((string) Session["Time"] );
    			
          }	
    }
    }
    
    您可能會注意到為加入這兩個 Web 方法啟用工作階段支援的 [WebMethod(EnableSession=true)] 屬性。
  2. 在 [建置] 功能表上按一下 建置方案


建立 ASP.NET 用戶端應用程式

當 Web 服務方法會使用工作階段狀態時,Cookie 會傳遞回給 Web 服務用戶端回應標頭中。該 Cookie 可唯一識別該 Web 服務用戶端的工作階段。若要接收該 Cookie Web 服務用戶端,必須被建立,呼叫 Web 服務方法之前,然後指派給 CookieContainer 屬性 CookieContainer 的新執行個體。如此可確保 Cookie 正確地包含在後續的要求。您必須進行此項操作,因為您必須儲存在根據此工作階段的未來擷取工作階段狀態中收到的 Cookie。要這麼做,請您執行下列步驟:
  1. 建立新的 ASP.NET Web 應用程式藉由使用 Visual C#.NET。專案 CookieContainerApp 的名稱。

    根據預設值,WebForm1.aspx,即建立。
  2. 在 [設計] 檢視中 WebForm1] 上按一下滑鼠右鍵,然後按一下 [檢視 HTML 原始檔]。
  3. Replace the existing code with the following code:
    <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="CookieContainerApp.WebForm1" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
       <HEAD>
          <title>WebForm1</title>
          <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
          <meta name="CODE_LANGUAGE" Content="C#">
          <meta name="vs_defaultClientScript" content="JavaScript">
          <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
       </HEAD>
       <body MS_POSITIONING="GridLayout">
          <form id="Form1" method="post" runat="server">
             <asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 270px; POSITION: absolute; TOP: 143px" runat="server" Text="SetTimeInSession" Width="187px"></asp:Button>
             <asp:Button id="Button2" style="Z-INDEX: 102; LEFT: 269px; POSITION: absolute; TOP: 203px" runat="server" Text="GetTimeFromSession"></asp:Button>
             <asp:Label id="Label1" style="Z-INDEX: 103; LEFT: 565px; POSITION: absolute; TOP: 150px" runat="server"></asp:Label>
             <asp:Label id="Label2" style="Z-INDEX: 104; LEFT: 565px; POSITION: absolute; TOP: 211px" runat="server"></asp:Label>
          </form>
       </body>
    </HTML>
    
  4. 在 [方案總管] 中以滑鼠右鍵按一下 [參考],然後按一下 [加入 Web 參考]。
  5. 在 [位址] 文字方塊中鍵入 WebService1 下列 URL:

    http://localhost/WebService1/Service1.asmx
  6. 按一下 開始,然後按一下 新增參考
  7. 在 [方案總管 的 WebForm1.aspx 上按一下滑鼠右鍵,然後按一下 [檢視程式碼
  8. WebForm1 中現有的程式碼取代下列程式碼:
    using System;
    using System.Web.UI.WebControls;
    
    namespace CookieContainerApp
    {
    	/// <summary>
    	/// Summary description for WebForm1.
    	/// </summary>
    	public class WebForm1 : System.Web.UI.Page
    	{
          protected System.Web.UI.WebControls.Button Button1;
          protected System.Web.UI.WebControls.Button Button2;
          protected System.Web.UI.WebControls.Label Label1;
          protected System.Web.UI.WebControls.Label Label2;
    
          // Create a new instance of a proxy class for your Web service.  
       	private localhost.Service1 objWSFunc = new localhost.Service1();
    
    		private void Page_Load(object sender, System.EventArgs e)
    		{
    			// Put user code to initialize the page here.
    		}
    
    		#region Web Form Designer generated code
    		override protected void OnInit(EventArgs e)
    		{
    			//
    			// CODEGEN:  Call required by ASP.NET Web Form Designer.
    			//
    			InitializeComponent();
    			base.OnInit(e);
    		}
    		
    		/// <summary>
    		/// Required method for Designer support. Do not modify.
    		/// The contents of this method with the code editor.
    		/// </summary>
    		private void InitializeComponent()
    		{    
             this.Button1.Click += new System.EventHandler(this.Button1_Click);
             this.Button2.Click += new System.EventHandler(this.Button2_Click);
             this.Load += new System.EventHandler(this.Page_Load);
    
          }
    		#endregion
    
          private void Button1_Click(object sender, System.EventArgs e)
          {
             System.Net.CookieContainer cookieJar = new System.Net.CookieContainer();
             
             // Assign the CookieContainer to the proxy class.  
             objWSFunc.CookieContainer = cookieJar;
    
             // Get CurrentTime.
             DateTime dt = DateTime.Now;
             string CurrentTime = dt.ToString("s"); 
             
             // Invoke a Web service method that uses session state and therefore cookies.  
             objWSFunc.SetTime(CurrentTime);
    
             // Store the cookies received in the session state for future retrieval by this session.  
             Session.Add("Time", cookieJar);
    
             Label1.Text="Time set in Session : " +CurrentTime ;
             Label2.Visible=false;
    
    
          }
    
          private void Button2_Click(object sender, System.EventArgs e)
          {
             // Get the SessionObject.
             objWSFunc.CookieContainer = (System.Net.CookieContainer) Session["Time"];          
    
             Label2.Visible=true;
             // Call the WebService method to access the session state.
             Label2.Text = "Time Get from Session : "+ objWSFunc.GetTime();
            
          }
           }
    }
    
  9. 在 [建置] 功能表上按一下 建置方案


藉由使用 CookieContainer 將內容新增到工作階段物件

  1. 在 [偵錯] 功能表上按一下 [[開始],以建置並執行應用程式]。
  2. 按一下 SetTimeInSession

    目前的時間值儲存在工作階段] 物件,並顯示目前的時間。

    在按鈕按一下事件,CookieContainer 物件會建立,然後指派給 Web 服務 Proxy CookieContainer 屬性。然後呼叫 Web 服務方法 SetTime() 來更新工作階段物件。


取得內容] 從工作階段物件藉由使用 CookieContainer

按一下 GetTimeFromSession。您可能會發現,當您呼叫網頁時,物件就會顯示工作階段中儲存的值,服務方法 GetTime() 時間。


?考

如需有關 CookieContainer 類別以及有關使用中 Web 服務的 ASP.NET 工作階段狀態的詳細資訊,請造訪下列 Microsoft 網站:

http://msdn2.microsoft.com/en-us/library/system.net.cookiecontainer(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/system.net.cookiecontainer(vs.71).aspx)

http://msdn2.microsoft.com/en-us/library/aa480509.aspx (http://msdn2.microsoft.com/en-us/library/aa480509.aspx)



這篇文章中的資訊適用於:
  • Microsoft Web Services (included with the .NET Framework) 1.0
  • Microsoft Web Services Enhancements for Microsoft .NET 1.1
  • Microsoft Visual C# .NET 2002 Standard Edition
  • Microsoft Visual C# .NET 2003 標準版
關鍵字:?
kbmt kbstate kbcookie kbwebservices kbwebserver kbwebforms kbhowtomaster KB816637 KbMtzh
機器翻譯機器翻譯
重要:本文是以 Microsoft 機器翻譯軟體翻譯而成,而非使用人工翻譯而成。Microsoft 同時提供使用者人工翻譯及機器翻譯兩個版本的文章,讓使用者可以依其使用語言使用知識庫中的所有文章。但是,機器翻譯的文章可能不盡完美。這些文章中也可能出現拼字、語意或文法上的錯誤,就像外國人在使用本國語言時可能發生的錯誤。Microsoft 不為內容的翻譯錯誤或客戶對該內容的使用所產生的任何錯誤或損害負責。Microsoft也同時將不斷地就機器翻譯軟體進行更新。
按一下這裡查看此文章的英文版本:816637? (http://support.microsoft.com/kb/816637/en-us/ )
Microsoft及(或)其供應商不就任何在本伺服器上發表的文字資料及其相關圖表資訊的恰當性作任何承諾。所有文字資料及其相關圖表均以「現狀」供應,不負任何擔保責任。Microsoft及(或)其供應商謹此聲明,不負任何對與此資訊有關之擔保責任,包括關於適售性、適用於某一特定用途、權利或不侵權的明示或默示擔保責任。Microsoft及(或)其供應商無論如何不對因或與使用本伺服器上資訊或與資訊的實行有關而引起的契約、過失或其他侵權行為之訴訟中的特別的、間接的、衍生性的損害或任何因使用而喪失所導致的之損害、資料或利潤負任何責任。