当源未实现 ContentLength 时,从另一个 Web 文件获取 HttpWebRequest 上传的响应长度以流式传输到上传中?
背景 - 我正在尝试使用 C# 中的 HttpWebRequest/HttpWebResponse 将现有网页流式传输到单独的 Web 应用程序。我注意到的一个问题是,我试图使用文件下载的内容长度来设置文件上传请求的内容长度,但是问题似乎是当源网页位于 HttpWebResponse 不支持的网络服务器上时提供内容长度。
HttpWebRequest downloadRequest = WebRequest.Create(new Uri("downloaduri")) as HttpWebRequest;
using (HttpWebResponse downloadResponse = downloadRequest.GetResponse() as HttpWebResponse)
{
var uploadRequest = (HttpWebRequest) WebRequest.Create(new Uri("uripath"));
uploadRequest.Method = "POST";
uploadRequest.ContentLength = downloadResponse.ContentLength; // ####
问题:我如何更新此方法来满足这种情况(当下载响应没有设置内容长度时)。也许会以某种方式使用 MemoryStream 吗?任何示例代码将不胜感激。
Background - I'm trying to stream an existing webpage to a separate web application, using HttpWebRequest/HttpWebResponse in C#. One issue I'm striking is that I'm trying to set the file upload request content-length using the file download's content-length, HOWEVER the issue seems to be when the source webpage is on a webserver for which the HttpWebResponse doesn't provide a content length.
HttpWebRequest downloadRequest = WebRequest.Create(new Uri("downloaduri")) as HttpWebRequest;
using (HttpWebResponse downloadResponse = downloadRequest.GetResponse() as HttpWebResponse)
{
var uploadRequest = (HttpWebRequest) WebRequest.Create(new Uri("uripath"));
uploadRequest.Method = "POST";
uploadRequest.ContentLength = downloadResponse.ContentLength; // ####
QUESTION: How could I update this approach to cater for this case (when the download response doesn't have a content-length set). Would it be to somehow use a MemoryStream perhaps? Any sample code would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您很乐意从其他网络服务器完全下载响应,那确实会让生活变得更轻松。当您从第一个 Web 服务器获取数据时,只需重复写入 MemoryStream,然后您就知道为第二个请求设置的长度,并且可以轻松写入数据(特别是
MemoryStream
有一个WriteTo
方法写入将其内容传输到另一个流)。这样做的缺点是,如果文件很大,您将占用大量内存。在您的情况下这可能是一个问题吗?替代方案包括:
MemoryStream
。当然,之后您需要清理文件 - 您基本上是在使用文件系统作为更大的内存:)If you're happy to download the response from the other web server completely, that would indeed make life easier. Just repeatedly write into a MemoryStream as you fetch from the first web server, then you know the length to set for the second request and you can write the data in easily (especially as
MemoryStream
has aWriteTo
method to write its contents to another stream).The downside of this is that you'll take a lot of memory if it's a large file. Is that likely to be a problem in your situation? Alternatives include:
MemoryStream
. You'll need to clean up the file afterwards, of course - you're basically using the file system as bigger memory :)