WinForm客户端调用 WebService时 如何启用Session

首先制作一个webservice服务并发布它

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

namespace MyService1
{
    /// <summary>
    /// Service1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod(EnableSession = true)]
        public string Test()
        {
            string name = Context.Session["username"].ToString();
            return name;
       
        }
        [WebMethod(EnableSession = true)]
        public void SetName(string strName)
        {
            Session["EmpName"] = strName;
        }

        [WebMethod(EnableSession = true)]
        public string GetName()
        {
            if (Session["EmpName"] == null)
            {
                return "";
            }
            else
            {
                return (string)Session["EmpName"];
            }
        }
    }
}

然后构建一个winform程序

WinForm客户端调用 WebService时 如何启用Session

 public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            System.Net.CookieContainer cc = new System.Net.CookieContainer();
            localhost.Service1 s1 = new localhost.Service1();
            s1.CookieContainer = cc;
            s1.SetName(textBox1.Text);
            label1.Text = s1.GetName();
          
        }

 

CookieContainer获取或设置与此请求关联的 cookie。

 

针对于webform的调用也是如此

 System.Net.CookieContainer cc=new System.Net.CookieContainer();
        Service.Service1 service = new Service.Service1();
        service.CookieContainer = cc;
        service.SetName("lijinchang");
        Response.Write(service.GetName());

你可能感兴趣的:(webservice)