【发布时间】:2020-01-04 10:53:46
【问题描述】:
我正在使用 .NET Core 3.1 开发 ASP.NET Web 应用程序。应用程序从外部网络服务器下载 mp3 文件,该服务器存在错误:响应标头中的 Content-Length 报告的字节数高于 mp3 的实际字节数。
这是一个使用 curl 从该服务器下载文件的示例:
curl -sSL -D - "http://example.com/test.mp3" -o /dev/null
HTTP/1.1 200 OK
Cache-Control: private
Pragma: no-cache
Content-Length: 50561024
Content-Type: audio/mpeg
Content-Range: bytes 0-50561023/50561024
Expires: 0
Accept-Ranges: 0-50561023
Server: Microsoft-IIS/10.0
Content-Transfer-Encoding: binary
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 03 Jan 2020 23:43:54 GMT
curl: (18) transfer closed with 266240 bytes remaining to read
因此,即使 curl 报告传输不完整,mp3 仍以 50294784 字节完全下载,我可以在任何我尝试过的音频播放器中打开它。
我想要在我的 Web 应用程序中实现与 curl 相同的行为:忽略不正确的 Content-Length 并下载 mp3,直到服务器关闭传输。
现在我只是使用 HttpClient 来异步下载 mp3:
internal static HttpClient httpClient = new HttpClient() { Timeout = new TimeSpan( 0, 15, 0 ) };
using( var response = await httpClient.GetAsync( downloadableMp3.Uri, HttpCompletionOption.ResponseContentRead ) )
using( var streamToReadFrom = await response.Content.ReadAsStreamAsync() )
但是,与 curl 不同的是,当传输过早关闭时,传输会整体中止:
Task <SchedulerTaskWrapper FAILED System.Net.Http.HttpRequestException: Error while copying content to a stream.
---> System.IO.IOException: The response ended prematurely.
at System.Net.Http.HttpConnection.FillAsync()
at System.Net.Http.HttpConnection.CopyToContentLengthAsync(Stream destination, UInt64 length, Int32 bufferSize, CancellationToken cancellationToken)
at System.Net.Http.HttpConnection.ContentLengthReadStream.CompleteCopyToAsync(Task copyTask, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionResponseContent.SerializeToStreamAsync(Stream stream, TransportContext context, CancellationToken cancellationToken)
at System.Net.Http.HttpContent.LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer)
--- End of inner exception stack trace ---
at System.Net.Http.HttpContent.LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer)
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
有什么方法可以配置 HttpClient 以“忽略”不正确的 Content-Length 并获取 mp3?
【问题讨论】:
标签: c# asp.net-core .net-core dotnet-httpclient