Search code examples
.netazurestorage

Blob in Azure Storage Reading as Zero Bytes


I've uploaded some files to Azure Storage. When I get a file's URL with an SAS and put the URL in a browser, I see the file. When I try to access the content from an Azure Functions App, the Content size is returned as zero bytes. The actual source file is about 3 megs. I've tried several methods of downloading the contents, but I keep encountering 0 byte response streams with response code 200. Any idea why this might be happening?

async Task<MemoryStream> GetUrlAsMemoryStream(String sourceUrl)
{
MemoryStream ms = new MemoryStream();
try
{

    var handler = new HttpClientHandler();
    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli;

    using (HttpClient httpClient = new HttpClient(handler))
    {
        httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
        httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "br");
        httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
        var response = await httpClient.GetAsync(sourceUrl);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"Error getting image from URL: {response.ReasonPhrase}");
        }
        var stream = await response.Content.ReadAsStreamAsync();
        await stream.CopyToAsync(ms);
        ms.Position = 0;
        if(ms.Length == 0)
            {  
            _logger.LogWarning($"The stream is empty::{sourceUrl}");
        }
        return ms;
    }
}
catch (Exception exc)
{
    _logger.LogError("Error getting image from URL", exc.Message);
    ms.Dispose();
    throw;
}
}

Solution

  • I don't know why this behaviour occurs. But when it happens, if I read the same URL again 200ms later then it succeeds. I ended up implementing a retry when I receive 0 byte streams.