.NET Core MVC中的部分内容(用于视频/音频流)

Cry*_*ana 6 c# asp.net-mvc streaming asp.net-core asp.net-core-webapi

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

这是返回FileStreamResult的Action的简化实现:

    public IActionResult GetFileDirect(string f)
    {
        var path = Path.Combine(Defaults.StorageLocation, f);
        return File(System.IO.File.OpenRead(path), "video/mp4");
    } 
Run Code Online (Sandbox Code Playgroud)

File方法具有以下(简短的)描述:

返回指定的fileStream(Status200OK)中的文件,并将指定的contentType作为Content-Type。这支持范围请求(如果范围不能满足,则为Status206PartialContent或Status416RangeNotSatisfiable)

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

我想念什么吗?


更新资料

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-
Run Code Online (Sandbox Code Playgroud)

响应如下:

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 ... ]
Run Code Online (Sandbox Code Playgroud)

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

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>
Run Code Online (Sandbox Code Playgroud)

视频开始播放-用户仅无法搜索视频。

Pau*_*ves 14

我的回答是基于 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;
} 
Run Code Online (Sandbox Code Playgroud)

这允许在浏览器中查找。


Yul*_*ner 6

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

在runtimeconfig.json中:

{
  // Set the switch here to affect .NET Core apps
  "configProperties": {
    "Switch.Microsoft.AspNetCore.Mvc.EnableRangeProcessing": "true"
  }
}
Run Code Online (Sandbox Code Playgroud)

要么:

 //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);
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参见ASP.NET Core GitHub Repo

  • 谢谢。我在Program.cs中设置了Switch,现在可以正常使用了! (2认同)