gpt4 book ai didi

c# - HttpClient 和 PushStreamContent

转载 作者:可可西里 更新时间:2023-11-01 09:10:54 27 4
gpt4 key购买 nike

我将 PushStreamContent 与我的 REST API (ASP.NET Web API) 结合使用并且效果很好。HttpClient 可以请求资源并在服务器处理完整请求之前获取 HTTP 响应(服务器仍然写入推送流)。

作为 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 是我的委托(delegate)类:

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

这是推送流所必需的。

这有可能吗?在将最后一个字节写入流之前,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 内容、TransportContext 上下文?

最佳答案

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

我要设置:httpWebRequest.AllowReadStreamBuffering = 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 makes HttpWebRequest/HttpClient behaviour unexpected)

对我有用的解决方案:

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 ...

关于c# - HttpClient 和 PushStreamContent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25429726/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com