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 回答