我正在尝试在我的网站上实现视频和音频流(启用Chrome in Chrome(,并且我最近发现.NET Core 2.0显然提供了一种相对简单的建议方法使用FileStreamResult
。
这是我简化的返回FileStreamResult的操作的实现:
public IActionResult GetFileDirect(string f)
{
var path = Path.Combine(Defaults.StorageLocation, f);
return File(System.IO.File.OpenRead(path), "video/mp4");
}
File
方法具有以下(缩短(描述:
以指定的FileStream(status200ok(返回文件,指定的ContentType作为Content-type。这支持范围请求(Status206-partialContent或status416rangenotsatible,如果范围不满足(
(
但是由于某种原因,服务器仍然无法正确响应范围请求。
我错过了什么吗?
更新
从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
并返回相同的响应。
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>
视频确实开始播放 - 用户只无法查找视频。
我的答案基于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;
}
这允许在浏览器中寻求。
将在版本2.1中的文件方法中添加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。