0

I am not that "sharp" in C#. Nevertheless I need this piece of code working. I have tried different things, nothing worked. The exceptions is being logged, it only misses the body of the response. Meaning it only log the headers.

How can I get the body as well. Below is what I have. The "messageFromServer" is what I have tried to use for the logging of the body (I found it here: https://stackoverflow.com/questions/11828843/webexception-how-to-get-whole-response-with-a-body#=).

Even tried using what was proposed here: C# - Getting the response body from a 403 error.

            catch (WebException ex)
            {
                var resp = (HttpWebResponse)ex.Response;

                Console.WriteLine("The transaction failed. Please see the logfile for full errorlog");
                File.AppendAllText("log_createtrxns.txt", "\r\nBOL\r\nDate" + headerDate + "\r\n Server body" + ex.Response + "\r\nAmount: " + decimalAmount + "\r\nData:" + ex.Data + "\r\nException: " + ex.Message + "\r\nSource: " + ex.Source + "\r\nStacktrace: " + ex.StackTrace + "\r\nEOL");
            }

That only gave me this in my logfile:

Server bodySystem.Net.HttpWebResponse

Sorry, but I simply do not understand how it should work together.

        try
        {
            response = (HttpWebResponse)httpWebRequest.GetResponse();

            foreach (string headerName in response.Headers)
            {
                //Console.WriteLine(headerName + ": " + response.Headers[headerName]);
            }

            var resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
            var messageFromServer = resp;

            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
            string result = readStream.ReadToEnd();
            Console.WriteLine(result);

            statusCode = (int) response.StatusCode;
            if (statusCode == 201)
            {
                String location = response.Headers["Location"];
                transId = Convert.ToInt32(location.Substring(location.LastIndexOf("/") + 1));
                Console.WriteLine("Transaction ID: " + transId);
            }

        }
        catch (Exception e)
        {
            Console.WriteLine("The transaction failed. Please see the logfile for full errorlog");
            File.AppendAllText("log_createtrxns.txt", "\r\nBOL\r\nDate" + headerDate + "\r\n Server body" + messageFromServer + "\r\nAmount: " + decimalAmount + "\r\nData:" + e.Data + transId + "\r\nException: " + e.Message + "\r\nSource: " + e.Source + "\r\nStacktrace: " + e.StackTrace + "\r\nEOL");
        }
Community
  • 1
  • 1
Kwire
  • 107
  • 1
  • 4
  • 12

0 Answers0