2017-04-04 203 views
0

我想發佈到WCF服務。我收到此錯誤 「在調用[Begin] GetResponse之前,您必須將ContentLength字節寫入請求流。」REST POST到WCF服務

代碼:

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

我想你需要經過移動的GetResponse關閉流(在StreamReader的using語句之後移動它) – Sparrow

+0

@Sparrow - 這將不起作用,很可能會導致OP代碼無法編譯。對'GetResponse'的調用用於在'using'塊中創建'StreamReader'。 – Tim

回答

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(); 
} 
+0

謝謝。我一直得到這個錯誤 – user1836442

+0

謝謝我保持這個錯誤「遠程服務器返回錯誤(404)沒有找到 – user1836442

+0

@ user1836442 - 聽起來像你有服務或端點的問題。 – Tim