HOW TO: Use CookieContainer to Maintain a State in Web Services When You Use Visual C# .NET (816637)



The information in this article applies to:

  • Microsoft Web Services (included with the .NET Framework) 1.0
  • Microsoft Web Services (included with the .NET Framework 1.1)
  • Microsoft Visual C# .NET (2002)
  • Microsoft Visual C# .NET (2003)

SUMMARY

This step-by-step article describes how to use the System.Net.CookieContainer class when you use sessions or cookies for a Web service in an application.

Although Web services are inherently stateless, you may use session objects to maintain stateful communication between a client application and a server application. To enable stateful communication between a Web client and the Web service, you may use the CookieContainer object with each message that is sent to the Web service from the client application. You may consume a stateful Web service in a state-enabled client application.

back to the top

Create a Web Service Application

  1. Run Microsoft Visual Studio .NET. Create a new ASP.NET Web service project by using Visual C# .NET.

    By default, Service1.asmx is created.
  2. Name the project WebService1.
  3. On the Build menu, click Build Solution.
back to the top

Enable Session Support on the Server

By default, ASP.NET session support for each Web service method is turned off. You must explicitly enable session support for each Web service method that requires a session state. To enable the session support, add the EnableSession property to the WebMethod attribute. To do this, follow these steps:
  1. In Solution Explorer, right-click Service1.asmx and then replace the existing code with the following code:
    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"] );
    			
          }	
    }
    }
    
    You may notice that the [WebMethod(EnableSession=true)] attribute is added for both Web methods to enable session support.
  2. On the Build menu, click Build Solution.
back to the top

Create an ASP.NET Client Application

When the Web service method uses a session state, a cookie is passed back to the Web service client in the response headers. That cookie uniquely identifies the session for that Web service client. To receive that cookie for the Web service client, a new instance of CookieContainer must be created and then assigned to the CookieContainer property before the Web service method is called. This makes sure that the cookie is correctly included in subsequent requests. You must do this because you must store the cookies that are received in the session state for future retrieval by this session. To do this, follow these steps:
  1. Create a new ASP.NET Web application by using Visual C# .NET. Name the project CookieContainerApp.

    By default, WebForm1.aspx is created.
  2. In Design view, right-click WebForm1 and then click View HTML Source.
  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. In Solution Explorer, right-click References and then click Add Web Reference.
  5. In the Address text box, type the following URL for WebService1:

    http://localhost/WebService1/Service1.asmx

  6. Click Go and then click Add Reference.
  7. In Solution Explorer, right-click WebForm1.aspx and then click View Code.
  8. Replace the existing code in WebForm1 with the following code:
    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. On the Build menu, click Build Solution.
back to the top

Add Content to a Session Object by Using CookieContainer

  1. On the Debug menu, click Start to build and to run the Application.
  2. Click SetTimeInSession.

    The current time value is stored in the session object, and the current time appears.

    In the button click event, the CookieContainer object is created and then is assigned to the Web service proxy CookieContainer property. Then the Web Service method SetTime() is called to update the session object.
back to the top

Get Content from the Session Object by Using CookieContainer

Click GetTimeFromSession. You may notice that the time value that is stored in the session object appears when you call the Web service method GetTime().

back to the top

REFERENCES

For more information about the CookieContainer class and about using ASP.NET Session State in a Web service, visit the following Microsoft Web sites:

http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemnetcookiecontainerclasstopic.asp

http://msdn.microsoft.com/library/en-us/dnservice/html/service08062002.asp

back to the top

Modification Type:MajorLast Reviewed:5/15/2003
Keywords:kbState kbCookie kbWebServices kbWebServer kbWebForms kbHOWTOmaster KB816637 kbAudDeveloper