2012-09-08 136 views
3

我想從WCF服務返回CookiesContainer對象,但是我無法返回。我可以從服務返回字符串。從WCF服務返回CookiesContainer對象

這裏是我的的Web.config

<?xml version="1.0" encoding="UTF-8"?> 
<configuration> 

<system.web> 
    <compilation debug="true" targetFramework="4.0" /> 
    <authentication mode="Windows"> 
     <forms cookieless="UseCookies" requireSSL="false" /> 
    </authentication> 
</system.web> 

<system.serviceModel> 

<services> 
    <service name="WcfService1.Service1" behaviorConfiguration="ServiceBehaviour"> 
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration="" contract="WcfService1.IService1" /> 

    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> 
    </service> 
</services> 

<behaviors> 
    <serviceBehaviors> 
    <behavior name="ServiceBehaviour"> 
    <!--behavior>--> 
     <serviceMetadata httpGetEnabled="true" /> 
     <serviceDebug includeExceptionDetailInFaults="true" /> 
    </behavior> 
    </serviceBehaviors> 
</behaviors> 

<client> 
    <endpoint address="http://localhost/WcfService1/Service1.svc" 
    binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1" 
    contract="ServiceReference1.IService1" name="BasicHttpBinding_IService1" /> 
</client> 

<bindings> 
    <basicHttpBinding> 
    <binding name="BasicHttpBinding_IService1" closeTimeout="00:01:00" 
     openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" 
     allowCookies="true" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" 
     maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" 
     messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" 
     useDefaultWebProxy="true"> 
     <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" 
     maxBytesPerRead="4096" maxNameTableCharCount="16384" /> 
     <security mode="None"> 
     <transport clientCredentialType="None" proxyCredentialType="None" 
      realm="" /> 
     <message clientCredentialType="UserName" algorithmSuite="Default" /> 
     </security> 
    </binding> 
    </basicHttpBinding> 
</bindings> 

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
</system.serviceModel> 

<system.webServer> 
    <modules runAllManagedModulesForAllRequests="true" /> 
</system.webServer> 

</configuration> 

這裏是我的 IService1.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.ServiceModel.Web; 
using System.Text; 
using System.Net; 
using System.IO; 
using System.Web; 

namespace WcfService1 
{ 
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together. 
[ServiceContract] 
public interface IService1 
{ 
    [OperationContract] 
    CookieCollection GetCookies(); 

    [OperationContract] 
    CookieContainer GetConnect(string uname, string password); 
    //string GetConnect(string uname, string password); 
} 
} 

這裏是我的Service1.svc.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.ServiceModel.Web; 
using System.Text; 
using System.Net; 
using System.IO; 
using System.Web; 

namespace WcfService1 
{ 
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together. 
public class Service1 : IService1 
{ 
    public CookieCollection GetCookies() 
    { 
     HttpWebRequest req; 
     CookieCollection cc = new CookieCollection(); 
     req = null; 

     req = (HttpWebRequest)WebRequest.Create("http://site5.way2sms.com/"); 
     req.CookieContainer = new CookieContainer(); 
     // req.CookieContainer.Add(cc); 

     req.CookieContainer.Add(cc); 
     req.KeepAlive = true; 

     req.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11"; 
     req.ContentType = "application/x-www-form-urlencoded"; 
     req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; 

     req.Referer = "http://site5.way2sms.com/content/index.html"; 

     req.AllowAutoRedirect = true; 
     req.ServicePoint.Expect100Continue = true; 

     return ((HttpWebResponse)req.GetResponse()).Cookies; 
    } 

    public CookieContainer GetConnect(string uid, string password) 
    //public string GetConnect(string uid, string password) 
    { 
     HttpWebRequest req; 
     HttpWebResponse res; 
     Stream str; 


     //try 
     //{ 
      req = (HttpWebRequest)WebRequest.Create("http://site5.way2sms.com/Login1.action"); 
      req.Method = "POST"; 
      CookieContainer con = new CookieContainer(); 
      req.CookieContainer = con; 
      req.CookieContainer.Add(GetCookies()); 
      req.KeepAlive = true; 

      req.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11"; 
      req.ContentType = "application/x-www-form-urlencoded"; 
      req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; 

      req.Referer = "http://site5.way2sms.com/content/index.html"; 

      byte[] data = System.Text.Encoding.Default.GetBytes("username=" + uid + "&password=" + password); 
      req.Credentials = new NetworkCredential(uid, password); 
      req.ContentLength = data.Length; 
      req.AllowAutoRedirect = true; 
      req.ServicePoint.Expect100Continue = true; 

      str = req.GetRequestStream(); 
      str.Write(data, 0, data.Length); 
      str.Close(); 


      res = (HttpWebResponse)req.GetResponse(); 

      string iduri = System.Web.HttpUtility.ParseQueryString(res.ResponseUri.Query).Get("id"); 

      if (iduri != "") 
      { 
       return con; 
       //return "Success"; 
      } 
      else 
      { 
       res.Close(); 
       str.Close(); 

       return null; 
       //return "Fail"; 
      } 
     //} 
     //catch (Exception ex) 
     //{ 

     //} 
    } 
    } 
} 

這裏是我的Login.xaml.cs

private void btnSignin_Click(object sender, RoutedEventArgs e) 
    { 
     string uid = txtUsername.Text.Trim(); 
     string password = txtPassword.Password.Trim(); 

     networkIsAvailable = Checknetwork(); 
     if (networkIsAvailable) 
     { 
      MessageBox.Show("Network Avaliable", "Avaliable", MessageBoxButton.OK); 
      //svc.GetcookiesCompleted += new EventHandler<GetcookiesCompletedEventArgs>(svc_Get_Cookies); 
      //svc.GetcookiesAsync(); 

      txtblockcheck.Visibility = Visibility.Visible; 
      svc.GetConnectCompleted += new EventHandler<GetConnectCompletedEventArgs>(svc_Get_Connected); 
      svc.GetConnectAsync(uid, password); 
     } 
     else 
     { 
      MessageBox.Show("Please check your network", "Warning", MessageBoxButton.OK); 
     } 
    } 


    void svc_Get_Connected(object send, GetConnectCompletedEventArgs e) 
    { 
     CookieContainer con = e.Result; 
    } 

當我從服務回報CookiesContainer我得到這個以下錯誤

有沒有終點在HTTP偵聽://本地主機:3922 /服務1 .svc可以接受該消息。這通常是由不正確的地址或SOAP操作引起的。有關更多詳細信息,請參閱InnerException(如果存在)。

我不明白我怎麼能從服務返回CookiesContainer對象到客戶端 可以anybuddy告訴我嗎?

+0

錯誤消息似乎與您建議的問題無關。 –

+0

當我返回CookieContainer對象時,它給出了我上面提到的錯誤 –

+0

我可以輕鬆地從服務返回字符串。但我無法返回cookies容器 –

回答

1

如果沒有別的,爲了幫助調試它,我會手動運行序列化。 CookieContainer不是XmlSerializable(但是是可序列化的Soap,所以不應該是真正的問題),但我絕對不喜歡發送除了通過web服務寫入的POCO對象以外的其他東西。

這裏是我的通用序列化方法,可能只是給它的字節數組,或Convert.ToBase64String()並返回。如果沒有別的,這將絕對確認您的web服務按預期工作。

使用方法,我有如下:

public byte[] GetConnect(string uid, string password) 
{ 
    ... 

    if (iduri != "") 
    { 
     return SerializeObject(con); 
    } 
} 

-

void svc_Get_Connected(object send, GetConnectCompletedEventArgs e) 
{ 
    CookieContainer con = DeserializeObject<CookieContainer >(e.Result); 
} 

-

public static byte[] SerializeObject<T>(T obj) 
{ 
    try 
    { 
     using (MemoryStream memoryStream = new MemoryStream()) 
     { 
      BinaryFormatter xs = new BinaryFormatter(); 
      xs.Serialize(memoryStream, obj); 

      return memoryStream.ToArray(); 
     } 
    } 
    catch 
    { 
     return null; 
    } 
} 
public static T DeserializeObject<T>(byte[] xml) 
{ 
    BinaryFormatter xs = new BinaryFormatter(); 
    MemoryStream memoryStream = new MemoryStream(xml); 
    return (T)xs.Deserialize(memoryStream); 
} 
+0

我不知道如何使用它? –

+0

已將更改添加到您的代碼 – Thymine

+0

如何在.xaml.cs文件中使用BinaryFormatter?我給出錯誤,即缺少程序集 –

0

那麼試試這個:

  1. 在您的客戶端項目中,轉到您的服務參考號,右鍵單擊,然後點擊更新服務參考。每次您對服務標誌(任何方法或參數)進行更改時,都必須更新此參考。也許你做了一些改變,忘記做這一步。

  2. 爲了以防萬一,在接口和服務定義中設置參數名稱等於。注意CookieContainer GetConnect(string uname, string password);在你定義接口指定string uname,但服務1執行聲明CookieContainer GetConnect(string uid, string password);,使用string uid。不應該是一個問題,而只是爲了整潔。

+0

我得到同樣的錯誤。該服務無法返回cookiecontainer對象。 –

+0

隔離它,我剛剛嘗試建立一個全新的解決方案,包括兩個項目,WCF和控制檯客戶端,使用相同的代碼,因爲它和它的工作。因此,使用默認配置**的代碼沒有任何問題。 – danielQ

+0

我如何分離它?你可以請你發佈你的代碼嗎?你的web.config,service1.svc,Iservice1.cs –