我试图重构一个使用SOAP获取一些API数据的控制台应用程序。我看到原始代码没有使用任何USING语句。我以为我会尝试重构代码来执行此操作,但是,我得到了一个"内部服务器错误"。我已经好几次看了这个,我也没看到为什么这样做不会起作用。如果我切换回原始代码,它会按预期工作。
这是有效的原始代码:
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;
}
这是我尝试使用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();
}
}
更新:基于回复的另一次尝试。这次在第二次USING声明中它表示我不能使用stream = response.GetResponseStream();
因为" stream"在使用声明中。
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;
答案 0 :(得分:1)
回答更新:
在using语句中声明的变量被视为readonly。我建议你声明一个新变量并将响应分配给它。为什么? - http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#relational-data
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;
应该有用。