How can I read the file contents using http synchronously

David Thielen 3,121 Reputation points
2023-09-16T17:37:58.9733333+00:00

In an event that is called synchronously, so I can't use await (so no IHttpClientFactory), what is the correct way to read the contents of a file.

I am using the following, and it works. But the compiler is telling me I should not use WebClient.

And to repeat, I have no choice in the matter - this cannot be an async method.

public byte[]? GetContent(IBlobService blobService, string blobUrl)
{
    using (var client = new WebClient())
    {
        return client.DownloadData(blobUrl);
    }
}

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,560 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 65,316 Reputation points
    2023-09-16T19:29:08.3133333+00:00

    why can't you use IHttpClientFactory? You can make the HttpClient async call sync with .GetAwaiter().GetResult().

    var buffer = httpClient.GetByteArrayAsync(blobUrl).GetAwaiter().GetResult();
    
    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.