ASP.NET Core断点续传
在ASP.NET WebAPi写过完整的断点续传文章,目前我对ASP.NET Core仅止于整体上会用,对于原理还未去深入学习,由于有园友想看断点续传在ASP.NET Core中的具体实现,于是借助在家中休息时间看了下ASP.NET Core是否支持断点续传以及支持后具体实现以及相关APi,花了一点时间,本文而由此而生。
断点续传基础
此前在ASP.NET WebAPi中对于一些基础内容已经详细讲解过,同时也进行了封装,所以再处理ASP.NET Core不过是APi使用不同罢了,断点续传重点在于AcceptRange和ContentRange以及对应响应请求头设置,其余和ASP.NET WebAPi使用别无二致。
在ASP.NET WebAPi中我们封装了对文件的操作接口IFileProvider和具体实现FileProvider,在控制器中我们是直接实例化,在ASP.NET Core中有了依赖注入,我们可直接借助控制器构造函数注入接口。
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddScoped<IFileProvider, FileProvider>();
}
当然前提是新建一个ASP.NET Core Web应用程序,然后我们新建一个DownLoadController控制器。在ASP.NET WebAPi中对于请求-响应机制对象是HttpRequestMessage和HttpResponseMessage,而在ASP.NET Core则是HttpRequest和HttpResponse对象。那么我们在控制器中如何获取这两个对象中呢?如果我们稍微有点经验的话就能明了请求和响应对象必然存储在上下文中,那么我们又如何获取上下文呢?通过IHttpContextAccessor接口获取。所以在控制器构造函数中获取文件接口和上下文以及对应的常量如下:
private const int BufferSize = 80 * 1024;
private const string MimeType = "application/octet-stream";
public IFileProvider _fileProvider { get; set; }
private IHttpContextAccessor _contextAccessor;
private HttpContext _context { get { return _contextAccessor.HttpContext; } }
public FileDownloadController(
IFileProvider fileProvider,
IHttpContextAccessor contextAccessor)
{
_fileProvider = fileProvider;
_contextAccessor = contextAccessor;
}
在ASP.NET WebAPi中获取请求头Range利用请求中的Headers属性获取,但在ASP.NET Core中则需要通过请求中的GetTypedHeaders()方法获取。
ASP.NET Core对于请求头中参数的获取和值的设置更加友好,比如我们要获取请求头中的请求类型,在ASP.NET WebAPi中我们指定字符串Request.Headers["Content-Type"],而在ASP.NET Core中则对应的是Request.Headers[HeaderNames.ContentType],直接通过枚举指定,如此一来则省事多了。最终在DownLoadController控制器中对于在ASP.NET Core中断点续传的整个逻辑如下:
public class FileDownloadController
{
private const int BufferSize = 80 * 1024;
private const string MimeType = "application/octet-stream";
public IFileProvider _fileProvider { get; set; }
private IHttpContextAccessor _contextAccessor;
private HttpContext _context { get { return _contextAccessor.HttpContext; } }
public FileDownloadController(
IFileProvider fileProvider,
IHttpContextAccessor contextAccessor)
{
_fileProvider = fileProvider;
_contextAccessor = contextAccessor;
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
[HttpGet("api/download")]
public IActionResult GetFile(string fileName)
{
fileName = "cn_windows_8_1_x64_dvd_2707237.iso";
if (!_fileProvider.Exists(fileName))
{
return new StatusCodeResult(StatusCodes.Status404NotFound);
}
//获取下载文件长度
var fileLength = _fileProvider.GetLength(fileName);
//初始化下载文件信息
var fileInfo = GetFileInfoFromRequest(_context.Request, fileLength);
//获取剩余部分文件流
var stream = new PartialContentFileStream(_fileProvider.Open(fileName),
fileInfo.From, fileInfo.To);
//设置响应 请求头
SetResponseHeaders(_context.Response, fileInfo, fileLength, fileName);
return new FileStreamResult(stream, new MediaTypeHeaderValue(MimeType));
}
/// <summary>
/// 根据请求信息赋予封装的文件信息类
/// </summary>
/// <param name="request"></param>
/// <param name="entityLength"></param>
/// <returns></returns>
private FileInfo GetFileInfoFromRequest(HttpRequest request, long entityLength)
{
var fileInfo = new FileInfo
{
From = 0,
To = entityLength - 1,
IsPartial = false,
Length = entityLength
};
var requestHeaders = request.GetTypedHeaders();
if (requestHeaders.Range != null && requestHeaders.Range.Ranges.Count > 0)
{
var range = requestHeaders.Range.Ranges.FirstOrDefault();
if (range.From.HasValue && range.From < 0 || range.To.HasValue && range.To > entityLength - 1)
{
return null;
}
var start = range.From;
var end = range.To;
if (start.HasValue)
{
if (start.Value >= entityLength)
{
return null;
}
if (!end.HasValue || end.Value >= entityLength)
{
end = entityLength - 1;
}
}
else
{
if (end.Value == 0)
{
return null;
}
var bytes = Math.Min(end.Value, entityLength);
start = entityLength - bytes;
end = start + bytes - 1;
}
fileInfo.IsPartial = true;
fileInfo.Length = end.Value - start.Value + 1;
}
return fileInfo;
}
/// <summary>
/// 设置响应头信息
/// </summary>
/// <param name="response"></param>
/// <param name="fileInfo"></param>
/// <param name="fileLength"></param>
/// <param name="fileName"></param>
private void SetResponseHeaders(HttpResponse response, FileInfo fileInfo,
long fileLength, string fileName)
{
response.Headers[HeaderNames.AcceptRanges] = "bytes";
response.StatusCode = fileInfo.IsPartial ? StatusCodes.Status206PartialContent
: StatusCodes.Status200OK;
var contentDisposition = new ContentDispositionHeaderValue("attachment");
contentDisposition.SetHttpFileName(fileName);
response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
response.Headers[HeaderNames.ContentType] = MimeType;
response.Headers[HeaderNames.ContentLength] = fileInfo.Length.ToString();
if (fileInfo.IsPartial)
{
response.Headers[HeaderNames.ContentRange] = new ContentRangeHeaderValue(fileInfo.From, fileInfo.To, fileLength).ToString();
}
}
}
总结
ASP.NET Core中FileResult、FileStreamResult、FilePhsicalResult都已支持断点续传,如果对于很小的文件直接下载即可,如果稍微大一点文件则可利用断点续传即可,如果对于非常大的文件则需要自定义流来下载这样更高效,比如对于获取视频流文件。上述我们依然是采取自定义流的形式来实现断点续传,若对其中封装的自定义流和接口有疑惑请移步右上角我的github参看ASP.NET WebAPi具体实现。无论是ASP.NET WebAPi和ASP.NET Core断点续传都实现了核心逻辑,对于一些细节未考虑其中,希望对想学习断点续传的您有所帮助,祝您阅读愉快,新年快乐!完整代码,我会上传到github!