如何使用http同步读取文件内容

问题描述 投票:0回答:1

在同步调用的事件中,所以我不能使用await(所以没有

IHttpClientFactory
),读取文件内容的正确方法是什么。

我正在使用以下内容,并且有效。但编译器告诉我不应该使用

WebClient

public byte[]? GetContent(IBlobService blobService, string blobUrl)
{
    using (var client = new WebClient())
    {
        return client.DownloadData(blobUrl);
    }
}
c# asp.net-core webclient dotnet-httpclient synchronous
1个回答
0
投票

.NET 5 HttpClient 开始,公开了一个名为

Send
的同步方法(
SendAsync
的非异步对应方法)。然后您可以在
ReadAsStream
上使用
HttpContent
同步方法来获取响应流。最后,可以使用
MemoryStream
将其转换为字节数组。

var client = new HttpClient();        
var request = new HttpRequestMessage(HttpMethod.Get, blobUrl);
var response = client.Send(request);

var responseStream = response.Content.ReadAsStream();       
using var memoryStream = new MemoryStream());
responseStream.CopyTo(memoryStream);
return memoryStream.ToArray();

仅当要下载的 blob 很小时才可以使用此方法。

© www.soinside.com 2019 - 2024. All rights reserved.