.NET HttpClient - 当响应头的 Content-Length 不正确时接受部分响应

Cos*_*sra 5 c# dotnet-httpclient .net-core asp.net-core

我正在使用 .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
Run Code Online (Sandbox Code Playgroud)

因此,即使 curl 报告传输不完整,mp3 也完全下载了 50294784 字节,我可以在我尝试过的任何音频播放器中打开它。

我在我的 Web 应用程序中想要的是与 curl 相同的行为:忽略不正确的 Content-Length 并下载 mp3,直到服务器关闭传输。

现在我只是使用 HttpClient 异步下载 mp3:

internal static HttpClient httpClient = new HttpClient() { Timeout = new TimeSpan( 0, 15, 0 ) };
Run Code Online (Sandbox Code Playgroud)
using( var response = await httpClient.GetAsync( downloadableMp3.Uri, HttpCompletionOption.ResponseContentRead ) )
using( var streamToReadFrom = await response.Content.ReadAsStreamAsync() )
Run Code Online (Sandbox Code Playgroud)

但是,与 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)
Run Code Online (Sandbox Code Playgroud)

有什么办法可以将 HttpClient 配置为“忽略”不正确的 Content-Length 并获取 mp3?

May*_*ayo 6

如果您查看dotnet 运行时存储库中的SendAsyncCore方法,您会看到相当大的代码,这些代码实现了发送请求和处理响应的核心功能。如果服务器发送 content-length 标头,则此方法在内部创建ContentLengthReadStream。该流需要固定数量的字节,并在达到预期数量之前被读取。如果 content-length 大于实际字节数,则ContentLengthReadStream将引发异常消息The response ended prematurely

由于所有这些方法都非常严格和内部,因此没有扩展或更改此功能的空间。但是有一个解决方法。您可以手动将流读入缓冲区,直到抛出异常。流的正常终止条件是 Read 方法返回零字节。如果 content-length 正确,则还应包括此条件。

using var resp = await httpClient.GetAsync("http://example.com/test.mp3", HttpCompletionOption.ResponseHeadersRead);
using var contentStream = await resp.Content.ReadAsStreamAsync();

var bufferSize = 2048;
var buffer = new byte[bufferSize];
var result = new List<byte>();

try
{
    var readBytes = 0;
    while ((readBytes = contentStream.Read(buffer)) != 0)
    {
        for (int i = 0; i < readBytes; i++)
        {
            result.Add(buffer[i]);
        }
    }
}
catch (IOException ex)
{
    if (!ex.Message.StartsWith("The response ended prematurely"))
    {
        throw;
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码将整个响应字节加载到 List 中result。对于大内容,这可能不是一个好的解决方案。

另请注意,HttpCompletionOption.ResponseContentRead在这种情况下不应使用,因为如果您调用GetAsync方法,它会尝试立即读取内容。由于我们要稍后阅读内容,因此应将其更改为 HttpCompletionOption.ResponseHeadersRead。这意味着GetAsync在读取标题时完成操作(尚未读取内容)。