Change PhysicalFileResult and VirtualFileResult to use SendFileAsync

- SendFileAsync does the proper fallback to stream copy when the feature
isn't available. Take advantage of it in MVC. There are plans to use the
buffer pool as part of the stream copy so MVC will get that benefit for
free.
- Left CopyToAsync in SendFileAsync when the file doesn't have a
physical path
This commit is contained in:
David Fowler 2015-12-31 15:28:50 -08:00
parent 2f66c041fd
commit 5aa2e06305
2 changed files with 4 additions and 50 deletions

View File

@ -3,10 +3,8 @@
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Mvc.Core;
using Microsoft.Net.Http.Headers;
@ -18,7 +16,6 @@ namespace Microsoft.AspNet.Mvc
/// </summary>
public class PhysicalFileResult : FileResult
{
private const int DefaultBufferSize = 0x1000;
private string _fileName;
/// <summary>
@ -83,52 +80,14 @@ namespace Microsoft.AspNet.Mvc
}
/// <inheritdoc />
protected override async Task WriteFileAsync(HttpResponse response)
protected override Task WriteFileAsync(HttpResponse response)
{
if (!Path.IsPathRooted(FileName))
{
throw new NotSupportedException(Resources.FormatFileResult_PathNotRooted(FileName));
}
var sendFile = response.HttpContext.Features.Get<IHttpSendFileFeature>();
if (sendFile != null)
{
await sendFile.SendFileAsync(
FileName,
offset: 0,
length: null,
cancellation: default(CancellationToken));
}
else
{
var fileStream = GetFileStream(FileName);
using (fileStream)
{
await fileStream.CopyToAsync(response.Body, DefaultBufferSize);
}
}
}
/// <summary>
/// Returns <see cref="Stream"/> for the specified <paramref name="path"/>.
/// </summary>
/// <param name="path">The path for which the <see cref="FileStream"/> is needed.</param>
/// <returns><see cref="FileStream"/> for the specified <paramref name="path"/>.</returns>
protected virtual Stream GetFileStream(string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
return new FileStream(
path,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite,
DefaultBufferSize,
FileOptions.Asynchronous | FileOptions.SequentialScan);
return response.SendFileAsync(FileName);
}
}
}

View File

@ -106,14 +106,9 @@ namespace Microsoft.AspNet.Mvc
if (fileInfo.Exists)
{
var physicalPath = fileInfo.PhysicalPath;
var sendFile = response.HttpContext.Features.Get<IHttpSendFileFeature>();
if (sendFile != null && !string.IsNullOrEmpty(physicalPath))
if (!string.IsNullOrEmpty(physicalPath))
{
await sendFile.SendFileAsync(
physicalPath,
offset: 0,
length: null,
cancellation: default(CancellationToken));
await response.SendFileAsync(physicalPath);
}
else
{