2010-10-12 68 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);     
      }