c# - 在 WCF Rest 中捕获 WebFaultException 的详细信息

标签 c# wcf exception rest

我有一个抛出 WebFaultException 的服务器

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:当我在 fiddler 中执行请求时,响应主体是详细信息,但由于在读取响应主体之前抛出该异常,因此它不会显示。所以问题是,尽管抛出了非 200,我如何读取响应正文。

Fiddler 原始响应:

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>

最佳答案

我只是在猜测,但我认为您只需要检查 GetResponse() 结果的 .StatusCode 成员并且不要尝试调用 GetResponseStream() 除非它是 200。如果它是一个错误代码(401 in你的情况),那么错误详细信息应该在 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;
}

关于c# - 在 WCF Rest 中捕获 WebFaultException 的详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3919583/

相关文章:

C# - 如何使用 Linq 和 Regex 实现单个字符串的多重匹配?

c# - 如何在 C# 中连接到 .NET Core 中的 Unix 域套接字

c# - 常规使用 soap 错误的 WCF 客户端的处置

java - 轴2 : Avoid "Unexpected subelement" error when non-required property added to WSDL

java - 如何从以下cataLog中找到异常?

java - 当我尝试读取 Excel 文件时出现 ClassNotFoundException

c# - 寻找比 MD5 或 SHA256 更快的 C# 哈希

c# - SSH,连接并执行 mysql 查询

.net - 使用 .NET 进行通知双向通信的方法

json - maxJsonLength超出了使用log4net ElasticSearch追加器进行的日志记录