我下面有一些API:
[Route("api/v1/video")]
public async Task<HttpResponseMessage> GetVideoContent()
{
const string fileName = "video.mp4";
var client = new RestClient("http://localhost:57243/");
var request = new RestRequest($"Assets/{fileName}");
request.AddHeader("Accept", "video/mp4");
var range = Request.Headers.Range.Ranges.First();
var from = range.From;
var to = range.To ?? 10;
request.AddHeader("Range", $"bytes={from}-{to}");
var memoryStream = new MemoryStream();
request.ResponseWriter = connectStream =>
{
connectStream.CopyTo(memoryStream);
};
await client.ExecuteGetTaskAsync(request);
var httpResponse = Request.CreateResponse();
httpResponse.Content = new StreamContent(memoryStream);
httpResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("video/mp4");
httpResponse.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
return httpResponse;
}
由下面的html调用:
<video width="100%" height="100%" controls="controls" autoplay="autoplay">
<source src="/api/v1/video" type="video/webm">
</video>
问题是执行上面的代码不会给Stream
头提供相应的ConnectStream
(后面的Range
),而是整个流... < / p>
如何使用Range标头仅获取此文件的一小部分?
这只是PoC,我不想利用File.OpenRead
或其他原因,因为它会破坏仅使用RestClient
来读取文件的整个目的。
注意:资产只是ASP.NET解决方案中的一个文件夹。