.NET Core MVC 中的部分内容(用于 video/audio 流式传输)

Partial content in .NET Core MVC (for video/audio streaming)

我正在尝试在我的网站上实现视频和音频流(以便在 Chrome 中进行搜索),我最近发现 .NET Core 2.0 显然提供了一种相对简单且推荐的实现方法,使用FileStreamResult.

这是我对 returns FileStreamResult:

操作的简化实现
    public IActionResult GetFileDirect(string f)
    {
        var path = Path.Combine(Defaults.StorageLocation, f);
        return File(System.IO.File.OpenRead(path), "video/mp4");
    } 

File 方法具有以下(缩写)描述:

Returns a file in the specified fileStream (Status200OK), with the specified contentType as the Content-Type. This supports range requests (Status206PartialContent or Status416RangeNotSatisfiable if the range is not satisfiable)

但由于某些原因,服务器仍然无法正确响应范围请求。

我是不是漏掉了什么?


更新

从 Chrome 发送的请求看起来像这样

GET https://myserver.com/viewer/GetFileDirect?f=myvideo.mp4 HTTP/1.1
Host: myserver.com
Connection: keep-alive
Accept-Encoding: identity;q=1, *;q=0
User-Agent: ...
Accept: */*
Accept-Language: ...
Cookie: ...
Range: bytes=0-

响应看起来像:

HTTP/1.1 200 OK
Server: nginx/1.10.3 (Ubuntu)
Date: Fri, 09 Feb 2018 17:57:45 GMT
Content-Type: video/mp4
Content-Length: 5418689
Connection: keep-alive

[... content ... ]

还尝试使用以下命令: curl -H Range:bytes=16- -I https://myserver.com/viewer/GetFileDirect?f=myvideo.mp4 和 returns 相同的响应。

HTML 也非常简单。

<video controls autoplay>
    <source src="https://myserver.com/viewer/GetFileDirect?f=myvideo.mp4" type="video/mp4">
    Your browser does not support the video tag.
</video>

视频确实开始播放 - 用户只是无法搜索视频。

2.1版本的File方法中会增加一个enableRangeProcessing参数。现在,您需要设置一个开关。您可以通过以下两种方式之一执行此操作:

在runtimeconfig.json中:

{
  // Set the switch here to affect .NET Core apps
  "configProperties": {
    "Switch.Microsoft.AspNetCore.Mvc.EnableRangeProcessing": "true"
  }
}

或:

 //Enable 206 Partial Content responses to enable Video Seeking from 
 //api/videos/{id}/file,
 //as per, https://github.com/aspnet/Mvc/pull/6895#issuecomment-356477675.
 //Should be able to remove this switch and use the enableRangeProcessing 
 //overload of File once 
 // ASP.NET Core 2.1 released

   AppContext.SetSwitch("Switch.Microsoft.AspNetCore.Mvc.EnableRangeProcessing", 
   true);

详情见ASP.NET Core GitHub Repo

我的回答基于 Yuli Bonner,但进行了改编以便直接回答问题,并且使用 Core 2.2

 public IActionResult GetFileDirect(string f)
{
   var path = Path.Combine(Defaults.StorageLocation, f);
   var res = File(System.IO.File.OpenRead(path), "video/mp4");
   res.EnableRangeProcessing = true;
   return res;
} 

这允许在浏览器中搜索。