使用 CookieContainer 使用 Visual C#.NET 时维护 Web 服务中的状态

来源:互联网 发布:深圳知豆电动汽车 编辑:程序博客网 时间:2024/06/05 06:33

本文分步介绍了如何使用该 System.Net.CookieContainer 类,应用程序中的 Web 服务使用会话或 Cookie 时。

尽管 Web 服务是本质上是无状态,您可以使用 Session 对象维护客户端应用程序和服务器应用程序之间的有状态通信。 若要启用 Web 客户端和 Web 服务之间的有状态通信,您可能会从客户端应用程序发送到 Web 服务的每个邮件使用 CookieContainer 对象。 您可能会占用状态启用客户端应用程序中有状态的 Web 服务。

创建 Web 服务应用程序

  1. 运行 Microsoft Visual Studio.NET。 创建新的 ASP.NET Web 服务项目,使用 Visual C#.NET。

    情况默认,创建 Service 1.asmx。
  2. 将该项目命名 WebService1
  3. 生成 菜单上单击 生成解决方案

 

启用服务器上的会话支持

默认,处于关闭状态为每个 Web 服务方法的 ASP.NET 会话支持。 必须显式启用需要会话状态的每个 Web 服务方法的会话支持。 若要启用该会话支持,请将 EnableSession 属性添加到 WebMethod 属性。 要这样做,请按下列步骤操作:

  1. 在解决方案资源管理器右键单击 Service 1.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 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"] );      }}}
    您可能注意到 [WebMethod(EnableSession=true)] 属性添加要启用会话支持两个 Web 方法的。
  2. 生成 菜单上单击 生成解决方案

 

创建 ASP.NET 客户端应用程序

当 Web 服务方法使用会话状态时,则会将 Cookie 传递回给 Web 服务客户端响应标头中。 该 Cookie 唯一标识的该 Web 服务客户端的会话。 为 Web 服务客户端接收的 Cookie, CookieContainer 的新实例必须创建并调用 Web 服务方法之前然后分配给 CookieContainer 属性。 这将确保正确中后续请求中包含该 Cookie。 您必须这样做,因为您必须存储在以后检索此会话的会话状态中收到的 Cookie。 要这样做,请按下列步骤操作:

  1. 创建新的 ASP.NET Web 应用程序使用 Visual C#.NET。 将该项目 CookieContainerApp 命名。

    情况默认,创建 WebForm 1.aspx。
  2. 设计 视图中右键单击 WebForm 1 ,然后单击 查看 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. 在解决方案资源管理器右键单击 WebForm 1.aspx ,然后单击 查看代码
  8. 替换为下面的代码的 WebForm 1 中的现有代码:
    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();              }       }}
  9. 生成 菜单上单击 生成解决方案


使用 CookieContainer 将内容添加到会话对象

  1. 调试 菜单中上, 单击 开始 ,以生成并运行应用程序。
  2. 单击 SetTimeInSession

    当前的时间值存储在会话对象中,当前时间显示。

    在按钮单击事件, CookieContainer 对象创建,并再分配给 Web 服务代理 CookieContainer 属性。 然后 Web 服务方法 SetTime() 调用来更新会话对象。

 

内容从获取会话对象使用 CookieContainer

单击 GetTimeFromSession 。 您可能发现的对象显示在调用 Web 会话中存储的值服务方法 GetTime() 时间。