Webexception How to Get Whole Response with a Body

WebException how to get whole response with a body?

var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();

dynamic obj = JsonConvert.DeserializeObject(resp);
var messageFromServer = obj.error.message;

Getting full response body from System.Net.WebRequest

You're catching the generic exception so there is not much room for specific info.

You should catch the specialized exception that is thrown by the several webrequest classes, namely WebException

Your catch code could be like this:

catch (WebException e)
{
var response = ((HttpWebResponse)e.Response);
var someheader = response.Headers["X-API-ERROR"];
// check header

if (e.Status == WebExceptionStatus.ProtocolError)
{
// protocol errors find the statuscode in the Response
// the enum statuscode can be cast to an int.
int code = (int) ((HttpWebResponse)e.Response).StatusCode;
string content;
using(var reader = new StreamReader(ex.Response.GetResponseStream()))
{
content = reader.ReadToEnd();
}
// do what ever you want to store and return to your callers
}
}

In the WebException instance you also have access to the Response send from the host, so you can reach anything that is being send to you.

WebClient - get response body on error status code

You cant get it from the webclient however on your WebException you can access the Response Object cast that into a HttpWebResponse object and you will be able to access the entire response object.

Please see the WebException class definition for more information.

Below is an example from MSDN (added reading the content of the web response for clarity)

using System;
using System.IO;
using System.Net;

public class Program
{
public static void Main()
{
try {
// Create a web request for an invalid site. Substitute the "invalid site" strong in the Create call with a invalid name.
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid URL");

// Get the associated response for the above request.
HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();
myHttpWebResponse.Close();
}
catch(WebException e) {
Console.WriteLine("This program is expected to throw WebException on successful run."+
"\n\nException Message :" + e.Message);
if(e.Status == WebExceptionStatus.ProtocolError) {
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
using (StreamReader r = new StreamReader(((HttpWebResponse)e.Response).GetResponseStream()))
{
Console.WriteLine("Content: {0}", r.ReadToEnd());
}
}
}
catch(Exception e) {
Console.WriteLine(e.Message);
}
}
}

WebException response didn't return the full response

I think you have access to active directory that's why code works on local but on IIS the application pool is running from ApplicationPoolIdentity which does not have access.

Go to the application pool and change the identity to your account. Here is an image for your reference:Sample Image

C# WebException Response Parsing Issues

After a lot of searching and digging I was able to determine that previously when creating the HttpWebRequest somewhere in the background it knew to automatically decompress Gzip for the responses.
However, after some indeterminate point in time, that instruction was left out which resulted in parsing errors.
Turns out it wasn't the result of incorrect codecs, or casting types or response calls, but that "Deflate Gzip" wasn't part of the request anymore afterwards.

Our fix was solved by making sure to add:

request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

I also threw in the bottom chunk of code down there for good measure.

request.KeepAlive = true;

Thanks to this post for saving hours of frustation: HTTP call in C# is returning garbage data in the response

Can't get ResponseStream from WebException

After a month of almost everyday thinking I've found workaround.

The thing was that WebException.Response.GetResponseStream() returns not exactly the same stream that was obtained during request (can't find link to msdn right now) and by the time we get to catch the exception and read this stream the actual response stream is lost (or something like that, don't really know and was unable to find any info on the net, except looking into CLRCore which is now opensource).

To save the actual response until catching WebException you must set KeepAlive Property on your HttpRequest and voila, you get your response while catching exception.
So the working code looks like that:

            try
{
var httpRequest = WebRequest.CreateHttp(Protocol + ServerUrl + ":" + ServerPort + ServerAppName + url);

if (HttpWebRequest.DefaultMaximumErrorResponseLength < int.MaxValue)
HttpWebRequest.DefaultMaximumErrorResponseLength = int.MaxValue;

httpRequest.ContentType = "application/json";
httpRequest.Method = method;
var encoding = Encoding.GetEncoding("utf-8");

if (httpRequest.ServicePoint != null)
{
httpRequest.ServicePoint.ConnectionLeaseTimeout = 5000;
httpRequest.ServicePoint.MaxIdleTime = 5000;
}
//----HERE--
httpRequest.KeepAlive = true;
//----------
using (var response = await httpRequest.GetResponseAsync(token))
{
using (var reader = new StreamReader(response.GetResponseStream(), encoding))
{
return await reader.ReadToEndAsync();
}
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
using (var response = (HttpWebResponse)ex.Response)
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream, Encoding.GetEncoding("utf-8")))
{
return reader.ReadToEnd();
//or handle it like you want
}
}
}
}
}

I don't know if it is good to keep all connection alive like that, but since it helped me to read actual responses from server, i think it might help someone, who faced the same problem.

EDIT: Also it is important not to mess with HttpWebRequest.DefaultMaximumErrorResponseLength.

How to obtain a web response exception stream when returned exception is AggregateException instead of WebException

It seems that I found a solution to my above problem. I amended example 1 to:

HttpClient myClient = new HttpClient;
Task<HttpResponseMessage> respTask1;
Task<byte[]> respTask2;
byte[] resultdata;
Uri reqUri = new Uri(query.ToString());
HttpRequestMessage webreq = new HttpRequestMessage(HttpMethod.Get, reqUri);
respTask1 = myClient.GetAsync(webreq.RequestUri, HttpCompletionOption.ResponseHeadersRead);
//only retrieve the headers at this stage, stream data will be retrieved below
httpmsg = respTask1.Result;
respTask2 = httpmsg.Content.ReadAsByteArrayAsync();
//now retrieve the response data in a second task
resultdata = respTask2.Result;

This code throws neither an AggregateException nor a HttpRequestException in case of "404 Not Found", so the absence of response stream in either of these is no problem. The "404 Not Found" code is in the response headers (I think it is the StatusCode header) and the associated response stream is in the byte array.



Related Topics



Leave a reply



Submit