我发现了我的问题。
我的代码顺序导致了问题。
解决方案是按以下顺序调用它:
- GetRequestStream(将异步写入流)(在第一次写入后将请求发送到服务器)然后:
- 获取响应异步()
- 获取响应流()
我的理解是“GetResponseAsync”会触发客户端发送请求(现在只有标头),但我发现这是一个不必要的步骤,因为在前几位写入后请求已经发送到溪流。
我的问题的第二个原因是 Fiddler,但 Fiddler 只支持响应流,而不支持请求。
代码实现了引用,'HttpWebRequest'类:
HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://xxx") as HttpWebRequest;
httpWebRequest.Method = "POST";
httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("user:pw"));
httpWebRequest.PreAuthenticate = true;
httpWebRequest.SendChunked = true;
httpWebRequest.AllowWriteStreamBuffering = false;
httpWebRequest.AllowReadStreamBuffering = false;
httpWebRequest.ContentType = "application/octet-stream";
Stream st = httpWebRequest.GetRequestStream();
Console.WriteLine("Go");
try
{
st.Write(buffer, 0, buffer.Length); //with the first write, the request will be send.
st.Write(buffer, 0, buffer.Length);
st.Write(buffer, 0, buffer.Length);
for (int i = 1; i <= 10; i++)
{
st.Write(buffer, 0, buffer.Length); //still writing while I can read on the stream at my ASP.NET web api
}
}
catch (WebException ex)
{
var y = ex.Response;
}
finally
{
st.Close();
}
// Now we can read the response from the server in chunks
Task<WebResponse> response = httpWebRequest.GetResponseAsync();
Stream resultStream = response.Result.GetResponseStream();
byte[] data = new byte[1028];
int bytesRead;
while ((bytesRead = resultStream.Read(data, 0, data.Length)) > 0)
{
string output = System.Text.Encoding.UTF8.GetString(data, 0, bytesRead);
Console.WriteLine(output);
}
代码实现了引用,'HttpClient'类:
HttpClientHandler ch = new HttpClientHandler();
HttpClient c = new HttpClient(ch);
c.DefaultRequestHeaders.TransferEncodingChunked = true;
c.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes("user:pw")));
Stream stream = new MemoryStream();
AsyncStream asyncStream = new AsyncStream(); // Custom implementation of the PushStreamContent with the method, "WriteToStream()".
PushStreamContent streamContent = new PushStreamContent(asyncStream.WriteToStream);
HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod("POST"), "http://XXX") { Content = streamContent };
requestMessage.Headers.TransferEncodingChunked = true;
HttpResponseMessage response = await c.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead);
// The request has been sent, since the first write in the "WriteToStream()" method.
response.EnsureSuccessStatusCode();
Task<Stream> result = response.Content.ReadAsStreamAsync();
byte[] data = new byte[1028];
int bytesRead;
while ((bytesRead = await result.Result.ReadAsync(data, 0, data.Length)) > 0)
{
string output = System.Text.Encoding.UTF8.GetString(data, 0, bytesRead);
Console.WriteLine(output);
}
Console.ReadKey();