This section describes how to useSystem. net. cookiecontainerClass, when the web service in the application uses session or cookie.
Although Web services are essentially stateless, you can use session objects to maintain stateful communication between client applications and server applications. To enable stateful communication between the Web Client and the web service, you may useCookiecontainerObject. You may use the status to enable stateful Web Services in the client application.
Create a Web Service Application
- Run Microsoft Visual Studio. NET. Create a new ASP. NET web service project and use Visual C #. net.
By default, Service 1. asmx is created.
- Name the project webservice1.
- InGenerateClickGenerate a solution.
Enable session support on the server
By default, ASP. NET session support is disabled for each web service method. You must explicitly enable session support for each web service method in the session state. To enable this session, setEnablesessionAdd propertyWebmethodAttribute. To do this, follow these steps:
- Right-click Solution ExplorerService 1. asmxAnd 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 codeprivate 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[Webmethod (enablesession = true)]Attribute to enable sessions that support two web methods.
- InGenerateClickGenerate a solution.
Create an ASP. NET client application
When the Web service method uses the session status, the cookie is passed back to the response header of the web service client. The session of the web service client uniquely identified by the cookie. The cookie received by the web service client,CookiecontainerThe new instance must be created and called before the Web service method is assignedCookiecontainerAttribute. This will ensure that the cookie is included in the correct subsequent requests. You must do this because you must store the cookies received in the session Status of this session to be retrieved later. To do this, follow these steps:
- Create a new ASP. NET web application using Visual C #. net. Name cookiecontainerapp of the project.
By default, webform 1. aspx is created.
- InDesignRight-clickWebform 1And then clickView HTML sources.
- 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>
- Right-click Solution ExplorerReferenceAnd then clickAdd web reference.
- InAddressThe following url is entered in the text box: http: // localhost/webservice1/service1.asmx
- ClickPositioningAnd then clickAdd reference.
- Right-click Solution ExplorerWebform 1. aspxAnd then clickView code.
- ReplaceWebform 1Existing Code in:
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 codeoverride 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(); } }}
- InGenerateClickGenerate a solution.
Use cookiecontainer to add content to a session object
- InDebuggingIn the menu, clickStartTo generate and run the application.
- ClickSettimeinsession.
The current time value is stored in the session object, and the current time is displayed.
Click the event button,CookiecontainerCreate an object and assign it to the Web Service proxy.CookiecontainerAttribute. Then the Web Service MethodSettime ()Call to update the session object.
Use cookiecontainer
ClickGettimefromsession. The objects you may find are displayed as value service methods stored in the call web session.Gettime ()Time.