请查看下面给出的代码。调试到达request.GetResponse()语句时,该错误已被抛出。远程服务器返回错误:(400)使用WCF服务时请求错误
Uri uri = new Uri(address);
string data = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><HasRole xmlns='http://tempuri.org/'><userName>" + sid + "</userName><role>" + role + "</role></HasRole></s:Body></s:Envelope>";
data.Replace("'", "\"");
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
if (uri.Scheme == Uri.UriSchemeHttps)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "POST";// WebRequestMethods.Http.Post;
request.ContentLength = byteData.Length;
request.ContentType = "application/soap+xml; charset=UTF-8"; // "text/xml; charset=utf-8";
//request.ContentType = "application/x-www-form-urlencoded";
//Stream requestStream = request.GetRequestStream();
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteData, 0, byteData.Length);
}
//writer.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
Response.Close();
Response.Write(tmp);
}
请问为什么神圣地球上您使用HttpWebRequest和手动伪造的HTTP请求,消耗WCF服务,而不是使用自动生成的强类型的代理(使用添加服务引用功能生成的一个在Visual Studio中)? –
这段代码有很多问题。 1)不使用“添加服务引用”,而是重新发明轮子 - 糟糕。 2)并非所有的IDisposable对象都处于“使用”块中。比如,StreamReader需要这个。 3)通过字符串操作而不是通过LINQ to XML或其他XML API来创建XML。 –