// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Mvc
{
///
/// Represents an that when executed will
/// write a file from a stream to the response.
///
public class FileStreamResult : FileResult
{
// default buffer size as defined in BufferedStream type
private const int BufferSize = 0x1000;
private Stream _fileStream;
///
/// Creates a new instance with
/// the provided and the
/// provided .
///
/// The stream with the file.
/// The Content-Type header of the response.
public FileStreamResult(Stream fileStream, string contentType)
: this(fileStream, MediaTypeHeaderValue.Parse(contentType))
{
}
///
/// Creates a new instance with
/// the provided and the
/// provided .
///
/// The stream with the file.
/// The Content-Type header of the response.
public FileStreamResult(Stream fileStream, MediaTypeHeaderValue contentType)
: base(contentType?.ToString())
{
if (fileStream == null)
{
throw new ArgumentNullException(nameof(fileStream));
}
FileStream = fileStream;
}
///
/// Gets or sets the stream with the file that will be sent back as the response.
///
public Stream FileStream
{
get
{
return _fileStream;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_fileStream = value;
}
}
///
protected async override Task WriteFileAsync(HttpResponse response)
{
var outputStream = response.Body;
using (FileStream)
{
var bufferingFeature = response.HttpContext.Features.Get();
bufferingFeature?.DisableResponseBuffering();
await FileStream.CopyToAsync(outputStream, BufferSize);
}
}
}
}