我试图发布到WCF服务。我收到这个错误 "在调用[Begin] GetResponse之前,必须将ContentLength字节写入请求流。"
代码:
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "patron=WTM";
byte[] data = encoding.GetBytes(postData);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8733/FileShareWebServices/UploadFile");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = data.Length;
httpWebRequest.GetRequestStream();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
答案 0 :(得分:0)
您发布的代码不会向请求流写入任何内容,这很可能是导致错误的原因。获得请求流后,您应该将内容和长度写入其中,如下所示:
using (Stream requestStream = httpWebRequest.GetRequestStream)
{
requestStream.Write(data, 0, data.Length);
}
完整的代码如下所示:
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "patron=WTM";
byte[] data = encoding.GetBytes(postData);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8733/FileShareWebServices/UploadFile");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = data.Length;
//httpWebRequest.GetRequestStream();
// Code to write data to the stream
using (Stream requestStream = httpWebRequest.GetRequestStream)
{
requestStream.Write(data, 0, data.Length);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}