Webサービス呼び出し時のセッション維持方法

基本的にWebサービスでは状態保存を行わないものとして設計するべきです。
ですが、大人の事情でやらざるを得ない場合があります(今ですが・・・)。


セッションを維持させるには、クライアント側でCookieContainerを生成してあげます。
呼び出し元をコンソールアプリとしてますが、当然Windowsアプリでも大丈夫。


WebService

namespace MyWebService
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod(EnableSession=true)]
        public int Addition(int value)
        {
            int ret = (int?)this.Session["value"] ?? 0;
            if (ret == 0)
            {
                ret = value;
            }
            else
            {
                ret += value;
            }
            this.Session["value"] = ret;

            return ret;
        }
    }
}


クライアント

namespace CallWebServiceByConsole
{
    class Program
    {
        [STAThread]
        static int Main(string[] args)
        {
            localhost.Service1 srv = new localhost.Service1();
            
            // CookieContainerがnullだとセッションを維持できない
            srv.CookieContainer = new System.Net.CookieContainer(); 
            for (int i = 1; i < 11; i++)
            {
                Console.WriteLine(i.ToString("00") + "回目結果: {0}", srv.Addition(i).ToString());
                System.Net.Cookie cookie = srv.CookieContainer.GetCookies(new Uri(srv.Url))[0];
                Console.WriteLine("Cookie Name:{0}, Value:{1}", cookie.Name, cookie.Value);

                if (i == 3)
                {
                    // 別セッションしてみる
                    srv.CookieContainer = new System.Net.CookieContainer();
                }
                else if (i == 6)
                {
                    // 別セッションしてみる
                    cookie.Value = "";
                }
            }
            Console.Read();
            return 0;
        }
    }
}

実行結果


01回目結果: 1
Cookie Name:ASP.NET_SessionId, Value:1jwj3k55hp4kh4edgiuevha1
02回目結果: 3
Cookie Name:ASP.NET_SessionId, Value:1jwj3k55hp4kh4edgiuevha1
03回目結果: 6
Cookie Name:ASP.NET_SessionId, Value:1jwj3k55hp4kh4edgiuevha1
04回目結果: 4
Cookie Name:ASP.NET_SessionId, Value:w4gtebzveodkcj55rrtmijbv
05回目結果: 9
Cookie Name:ASP.NET_SessionId, Value:w4gtebzveodkcj55rrtmijbv
06回目結果: 15
Cookie Name:ASP.NET_SessionId, Value:w4gtebzveodkcj55rrtmijbv
07回目結果: 7
Cookie Name:ASP.NET_SessionId, Value:audntq55mey1qy45p2u0lf55
08回目結果: 15
Cookie Name:ASP.NET_SessionId, Value:audntq55mey1qy45p2u0lf55
09回目結果: 24
Cookie Name:ASP.NET_SessionId, Value:audntq55mey1qy45p2u0lf55
10回目結果: 34
Cookie Name:ASP.NET_SessionId, Value:audntq55mey1qy45p2u0lf55

4回目と7回目でリセットされてますね。