1

WCF 4.5 で IHttpCookieContainerManager を使用する方法を知りたかっただけです。サンプルコードを提案してください。

4

1 に答える 1

1

.NET 4.5 では、AllowCoookies = true の場合、以下のように .GetProperty().CookieContainer メソッドを使用して Cookie コンテナーにアクセスできます。

        Uri serverUri = new Uri("http://localhost/WcfService/Service1.svc");
        CookieContainer myCookieContainer = new CookieContainer();
        myCookieContainer.Add(serverUri, new Cookie("cookie1", "cookie1Value"));

        ChannelFactory<IService1> factory = new ChannelFactory<IService1>(new BasicHttpBinding() { AllowCookies = true }, new EndpointAddress(serverUri));
        IService1 client = factory.CreateChannel();
        factory.GetProperty<IHttpCookieContainerManager>().CookieContainer = myCookieContainer;


        Console.WriteLine(client.GetData(123));

        myCookieContainer = factory.GetProperty<IHttpCookieContainerManager>().CookieContainer;
        foreach (Cookie receivedCookie in myCookieContainer.GetCookies(serverUri))
        {
            Console.WriteLine("Cookie name : " + receivedCookie.Name + " Cookie value : " + receivedCookie.Value);
        }

        ((IChannel)client).Close();
        factory.Close();

//サーバ側

public class Service1 : IService1
   {
    public string GetData(int value)
    {
        //Read the cookies
        HttpRequestMessageProperty reqProperty = (HttpRequestMessageProperty)OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name];
        string cookies = reqProperty.Headers["Cookie"];

        //Write a cookie
        HttpResponseMessageProperty resProperty = new HttpResponseMessageProperty();
        resProperty.Headers.Add("Set-Cookie", string.Format("Number={0}", value.ToString()));
        OperationContext.Current.OutgoingMessageProperties.Add(HttpResponseMessageProperty.Name, resProperty);
        return string.Format("You entered: {0}", value);
    }
}
于 2013-02-18T19:00:43.757 に答える