2013-02-15 47 views

回答

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); 
    } 
} 
+0

通過在OperationContext.Current.OutgoingMessageProperties設置將繼續像以前一樣工作注意cookie管理的舊樣式。 – Praburaj 2013-02-18 19:02:01