ASP.NET Core FileStreamResult sometimes fails when writing big blob (~1gb) to response
...
Azure.Storage.Blobs.BlobClient blob = container.GetBlobClient(fileName)
Stream stream = await blob.OpenReadAsync().ConfigureAwait(false);
return File(stream, MediaTypeNames.Application.Octet, fileName);
Logged error (occurs inside FileStreamResultExecutor):
System.ArgumentNullException: Value cannot be null. (Parameter 'buffer')
at System.Net.Http.HttpBaseStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
at Azure.Core.Pipeline.ReadTimeoutStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
at Azure.Core.Pipeline.RetriableStream.RetriableStreamImpl.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
at Azure.Core.Pipeline.RetriableStream.RetriableStreamImpl.RetryAsync(Exception exception, Boolean async, CancellationToken cancellationToken)
at Azure.Core.Pipeline.RetriableStream.RetriableStreamImpl.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
at Azure.Storage.LazyLoadingReadOnlyStream`1.DownloadInternal(Boolean async, CancellationToken cancellationToken)
at Azure.Storage.LazyLoadingReadOnlyStream`1.ReadInternal(Byte[] buffer, Int32 offset, Int32 count, Boolean async, CancellationToken cancellationToken)
at Azure.Storage.LazyLoadingReadOnlyStream`1.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Http.StreamCopyOperationInternal.CopyToAsync(Stream source, Stream destination, Nullable`1 count, Int32 bufferSize, CancellationToken cancel)
at Microsoft.AspNetCore.Internal.FileResultHelper.WriteFileAsync(HttpContext context, Stream fileStream, RangeItemHeaderValue range, Int64 rangeLength)
Platform: Windows, .NET 6
Another approach is to check if the stream is null before passing it to the
FileStreamResult. You can add a null check before returning theFileStreamResultto ensure that the stream is not null.To check if the stream is null before returning the
FileStreamResultYou can increase the buffer size by setting the
ResponseBufferSizeproperty in theKestrelServerOptionsSet theResponseBufferSizeproperty to 1 GB.Another approach
You can use the
PushStreamContentclass instead ofFileStreamResultto stream the file to the response.PushStreamContent
For further information refer to the MSDoc.