HttpClient and PushStreamContent

本文关键字:PushStreamContent and HttpClient | 更新日期: 2023-09-27 18:18:56

我使用PushStreamContent与我的REST API (ASP。. NET Web API)并且工作得很好。HttpClient可以请求资源并在服务器处理完整的请求之前获得HTTP-Response(服务器仍然写入推送流)。

作为HttpClient,你必须做一件小事:使用HttpCompletionOption.ResponseHeadersRead.

现在我的问题是:有没有可能用另一种方法?从HttpClient ->上传数据通过推流到web api?

我实现它如下,但web api得到的请求不是在客户端关闭流。

         var asyncStream = new AsyncStream(fs);
         PushStreamContent streamContent = new PushStreamContent(asyncStream.WriteToStream);
         content.Add(streamContent);
         HttpResponseMessage response = await c.SendAsync(new HttpRequestMessage(new HttpMethod("POST"), "http://localhost/...") { Content = content }, HttpCompletionOption.ResponseHeadersRead);
         response.EnsureSuccessStatusCode();

AsyncStream是我的类与委托:

public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)

这对于Push-Stream是必需的。

这可能吗?HttpClient不会将请求发送到web api,直到最后一个字节被写入流…

我该怎么做?问题是在客户端还是在服务器/asp.net web api端?

编辑:这是WriteToStream的实现(但我不使用磁盘上的文件,而是使用内存流'myMemoryStream'(在构造函数中传递):

public void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
{
    try
    {
        var buffer = new byte[4096];
        using (var stream = myMemoryStream)
        {
            var bytesRead = 1;
            while (bytesRead > 0)
            {
                bytesRead = video.Read(buffer, 0, buffer.Length);
                outputStream.Write(buffer, 0, bytesRead);
            }
        }
    }
    catch (HttpException ex)
    {
        return;
    }
    finally
    {
        outputStream.Close();
    }
}

也许我需要做一些事情:HttpContent content, TransportContext context ?

HttpClient and PushStreamContent

我找到了解决问题的方法:

我想设置:httpWebRequest。allowreadstreambuffer = false;

HttpClient 4.0默认做缓冲,你不能访问属性AllowReadStreamBuffering,所以你必须直接使用HttpWebRequest。(或者你可以使用HttpClinet 4.5,有默认行为'流')见:http://www.strathweb.com/2012/09/dealing-with-large-files-in-asp-net-web-api/6。使用HttpClient)

第二个问题是fiddler: fiddler目前只支持响应流而不支持请求流(fiddler使HttpWebRequest/HttpClient行为不可预测)

为我工作的解决方案:

HttpWebRequest httpWebRequest = HttpWebRequest.Create(...)
httpWebRequest.Method = "POST";
         httpWebRequest.Headers["Authorization"] = "Basic " + ...;
         httpWebRequest.PreAuthenticate = true;
         httpWebRequest.AllowWriteStreamBuffering = false;
         httpWebRequest.AllowReadStreamBuffering = false;
         httpWebRequest.ContentType = "application/octet-stream";
         Stream st = httpWebRequest.GetRequestStream();
st.Write(b, 0, b.Length);
st.Write(b, 0, b.Length);
//...
         Task<WebResponse> response = httpWebRequest.GetResponseAsync();
         var x = response.Result;
         Stream resultStream = x.GetResponseStream();
//... read result-stream ...

确保在请求消息上执行requestMessage.Headers.TransferEncodingChunked = true;…原因是,如果你不设置这个,HttpClient将缓冲整个内容在客户端本身,以找出请求的内容长度,这就是你注意到你的web api服务没有被立即调用的原因,因为你正在写入流…

相关文章:
  • 没有找到相关文章