加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:38:42 所属栏目:百科 来源:网络整理
导读:我有一个抛出WebFaultException的服务器 try{ ...}catch (InvalidPasswordException){ throw new WebFaultExceptionString ("This is a bad password",HttpStatusCode.Unauthorized);} 到现在为止还挺好.但是当这个WebFault被另一个C#项目(客户端)捕获时,我
我有一个抛出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中执行请求时,响应主体是详细信息但是在响应主体被读取之前抛出该异常然后它没有显示.所以问题是如何阅读响应主体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>

解决方法

我只是猜测,但我认为你只需要检查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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读