Caverman Caverman - 21 days ago 5
C# Question

Processing SOAP request with USING statement not working?

I'm trying to refactor a console app that uses SOAP to get some API data. I saw that the original code isn't using any USING statements. I thought I would try to refactor the code to do so, however, I get an "Internal Server Error". I've looked this over an few times and I'm not seeing why this wouldn't work. If I switch back to the original code it works as expected.

This is the original code that works:

public static string ProcessSOAPRequest(string xml, string endPoint)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(endPoint);
req.Timeout = 100000000;
req.Method = "POST";

Stream objStream = req.GetRequestStream();
doc.Save(objStream);
objStream.Close();

WebResponse resp = req.GetResponse();
objStream = resp.GetResponseStream();

StreamReader r = new StreamReader(objStream);
string data = r.ReadToEnd();

return data;
}


This is my attempt at refactoring with USING.

public static string ProcessSOAPRequest(string xml, string endPoint)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Timeout = 100000000;
request.Method = "POST";

using (WebResponse response = request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}


UPDATE: another attempt based on the responses. This time in the second USING statement it says that I can't use
stream = response.GetResponseStream();
because "stream" is in a using statement.

var data = string.Empty;
using (Stream stream = request.GetRequestStream())
{
doc.Save(stream);

using (WebResponse response = request.GetResponse())
{
stream = response.GetResponseStream();

using (StreamReader reader = new StreamReader(stream))
{
data = reader.ReadToEnd();
}
}
}

return data;

Answer

Answer to the update:

The variable declared in a using statement is treated as readonly. I suggest you to declare a new variable and assign the response to that. Why? - Why is a variable declared in a using statement treated as readonly?

var data = string.Empty;
using (Stream stream = request.GetRequestStream())
{
    doc.Save(stream);

    using (WebResponse response = request.GetResponse())
    {
        var responseStream = response.GetResponseStream();
        if (responseStream != null)
        {
            using (StreamReader reader = new StreamReader(responseStream))
            {
                data = reader.ReadToEnd();
            }
        }
    }
}            

return data;

should work.