2010-10-12 67 views
3

接住一個WebFaultException的細節我有拋出WebFaultException在WCF休息

try 
{ 
    ... 
} 
catch (InvalidPasswordException) 
{ 

    throw new WebFaultException<String> 
        ("This is a bad password", 
        HttpStatusCode.Unauthorized); 
} 

到目前爲止一切順利的服務器。但是,當這個WebFault被另一個C#項目(客戶端)捕獲時,我不知道如何獲取細節。

try 
{ 
    HttpWebRequest httpWebRequest = WebRequest.Create(uri) as HttpWebRequest; 

    httpWebRequest.Method = verb; 
    httpWebRequest.ContentType = "text/xml"; 
    httpWebRequest.ContentLength = serializedPayload.Length; 

    using (StreamWriter streamOut = new StreamWriter(httpWebRequest.GetRequestStream(), Encoding.ASCII)) 
    { 
     streamOut.Write(serializedPayload); 
     streamOut.Close(); 
    } 

    // error here on GetResponseStream 
    using (StreamReader streamIn = new StreamReader(httpWebRequest.GetResponse().GetResponseStream())) 
    { 
      string strResponse = streamIn.ReadToEnd(); 
      streamIn.Close(); 
      return strResponse; 
    } 
} 
catch (Exception e) 
{ 
    // The exception is of type WebException with unauthorized but don't know where the details are 
} 

此代碼捕獲WebException,我找不到詳細信息,只是未經授權。

感謝

更新1:當我做小提琴手請求的響應體是細節,但作爲例外的是響應體之前拋出的是讀過那麼它沒有顯示出來。所以問題是我如何閱讀響應主體DESPITE一個非200被拋出。

提琴手原始響應:

HTTP/1.1 401 Unauthorized 
Server: ASP.NET Development Server/10.0.0.0 
Date: Tue, 12 Oct 2010 22:42:31 GMT 
X-AspNet-Version: 4.0.30319 
Content-Length: 100 
Cache-Control: private 
Content-Type: application/xml; charset=utf-8 
Connection: Close 

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Email/Password Mismatch</string> 
+0

什麼是你的客戶?它是一個Web應用程序,或者一個Silverlight應用程序? – 2010-10-12 23:18:02

+0

C#.NET 4.0,windows窗體 – 2010-10-12 23:28:35

回答

4

我只是猜測,但我認爲你只需要檢查的GetResponse()的結果.StatusCode成員,不要試圖打電話的GetResponseStream( ),除非它是200.如果它是一個錯誤代碼(在你的情況下爲401),那麼錯誤細節應該在GetResponse()的.Content成員中。

喜歡的東西:

var r = httpWebRequest.GetResponse(); 
if(r.StatusCode != 200) 
{ 
    MessageBox.Show(r.Content); // Display the error 
} 
else 
{ 
    var streamIn = new StreamReader(r.GetResponseStream()); 
    string strResponse = streamIn.ReadToEnd(); 
    streamIn.Close(); 
    return strResponse; 
} 
3

引發WebException有可以轉換爲HttpWebResponse,然後調用的GetResponseStream上的響應性能。

在相關說明上,從WCF REST Starter套件中獲取Microsoft.Http庫,它是一種更好的客戶端庫,即HttpWebRequest/Response。有關詳細信息,我有一些博客文章在這裏:http://www.bizcoder.com/index.php/2009/12/08/why-the-microsoft-http-library-is-awesome/

+0

啊很酷,不知道這個庫。 TY – 2010-10-14 21:15:58

0

我用這個

try 
      { 
       //wcf service call 
      } 
      catch (FaultException ex) 
      { 
       throw new Exception((ex as WebFaultException<MyContractApplicationFault>).Detail.MyContractErrorMessage);     
      }