如何在WCF 4.5中使用IHttpCookieContainerManager

如何在WCF 4.5中使用IHttpCookieContainerManager,wcf,Wcf,只是想知道如何在WCF 4.5中使用IHttpCookieContainerManager。请推荐任何示例代码。在.NET 4.5中,如果AllowCookies=true,您可以使用下面的.GetProperty().CookieContainer方法访问cookie容器 Uri serverUri = new Uri("http://localhost/WcfService/Service1.svc"); CookieContainer myCookieCon

只是想知道如何在WCF 4.5中使用IHttpCookieContainerManager。请推荐任何示例代码。

在.NET 4.5中,如果AllowCookies=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();

在.NET 4.5中,如果AllowCookies=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();

通过在OperationContext.Current.OutgoingMessageProperties中的设置来记录旧样式的cookie管理将继续像以前一样工作。通过在OperationContext.Current.OutgoingMessageProperties中设置来记录旧样式的cookie管理将继续像以前一样工作。