这是我用来在 C# (MVC) 中创建 Web API 控制器的解决方案,它将提供具有字节范围(部分请求)的视频文件。部分请求允许浏览器只下载它需要播放的视频,而不是下载整个视频。这使其效率更高。
请注意,这只适用于最新版本。
var stream = new FileStream(videoFilename, FileMode.Open, FileAccess.Read , FileShare.Read);
var mediaType = MediaTypeHeaderValue.Parse($"video/{videoFormat}");
if (Request.Headers.Range != null)
{
try
{
var partialResponse = Request.CreateResponse(HttpStatusCode.PartialContent);
partialResponse.Content = new ByteRangeStreamContent(stream, Request.Headers.Range, mediaType);
return partialResponse;
}
catch (InvalidByteRangeException invalidByteRangeException)
{
return Request.CreateErrorResponse(invalidByteRangeException);
}
}
else
{
// If it is not a range request we just send the whole thing as normal
var fullResponse = Request.CreateResponse(HttpStatusCode.OK);
fullResponse.Content = new StreamContent(stream);
fullResponse.Content.Headers.ContentType = mediaType;
return fullResponse;
}