Finding WebFaultException objects in WCF Rest

I have a server that throws a WebFaultException

try
{
    ...
}
catch (InvalidPasswordException)
{

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

So far so good. However, when this WebFault gets into another C # project (client), I don't know how to get the information.

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
}

This code catches a WebException, which I cannot find details about, just unauthorized.

thank

UPDATE 1: When I make a request in a violin, the response body is a part, but since this exception is thrown before the response body is ever read, it does not appear. So the question is how I read the body of the DESPITE answer, which is not 200.

Fiddler Raw Response:

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>
+3
source share
3 answers

, , .StatusCode GetResponse() GetResponseStream(), 200. (401 ), .Content- GetResponse().

- :

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;
}
+4

WebException Response, HttpWebResponse, GetResponseStream.

Microsoft.Http Starter WCF REST, , HttpWebRequest/Response. : http://www.bizcoder.com/index.php/2009/12/08/why-the-microsoft-http-library-is-awesome/

+3

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

Source: https://habr.com/ru/post/1769247/


All Articles