这是我用来在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
{
var fullResponse = Request.CreateResponse(HttpStatusCode.OK);
fullResponse.Content = new StreamContent(stream);
fullResponse.Content.Headers.ContentType = mediaType;
return fullResponse;
}