使用 ASP.NET Core 7 Web API 缓冲/卡顿的相机流,有什么改进方法吗?

问题描述 投票:0回答:1

我们有一个在带有 IIS 的 Windows Server 上运行的 .NET 7 应用程序,该应用程序将来自摄像机的源返回到前端,但与在服务器上的 chrome 中查看的原始输出相比,返回的流非常断断续续。

是否可以对 IIS 中的代码或配置进行任何其他更改,以使其运行更顺畅?

在服务器上的 Chrome 中从原始摄像机 URL 观看流工作顺利,因此这似乎是 .NET 处理流的问题。

到目前为止,这就是我们返回的方式:

[HttpGet("{cameraId}")]
public async Task<ActionResult> StreamCamera(int cameraId)
{
    var camera = _context.Cameras.FirstOrDefault(item => item.Id == cameraId);

    if (camera == null)
    {
        return NotFound($"No camera found for id {cameraId}");
    }

    using var stream = await httpClient.GetStreamAsync(camera.cameraUrl);

    Response.ContentType = "multipart/x-mixed-replace; boundary=myboundary";

    await stream.CopyToAsync(Response.Body);

    return new HttpStatusCodeResult(200);
}

然后使用 img 在前端使用它

<img src="/api/camera/1" />
asp.net-core .net-core iis dotnet-httpclient .net-7.0
1个回答
0
投票

找到了一个可能的答案,在 Get 请求开始时,我在

DisableBuffering
功能中使用
HttpContext
方法,现在返回的流很平滑,没有延迟/缓冲。

不确定这是否是最好的方法或放置它的正确位置,但它已经解决了问题。

    var features = HttpContext.Features.Get<IHttpResponseBodyFeature>();
    features?.DisableBuffering();
[HttpGet("{cameraId}")]
public async Task<ActionResult> StreamCamera(int cameraId)
{
    // Added this here
    var features = HttpContext.Features.Get<IHttpResponseBodyFeature>();
    features?.DisableBuffering();

    var camera = _context.Cameras.FirstOrDefault(item => item.Id == cameraId);

    if (camera == null)
    {
        return NotFound($"No camera found for id {cameraId}");
    }

    using var stream = await httpClient.GetStreamAsync(camera.cameraUrl);

    Response.ContentType = "multipart/x-mixed-replace; boundary=myboundary";

    await stream.CopyToAsync(Response.Body);

    return new HttpStatusCodeResult(200);
}
© www.soinside.com 2019 - 2024. All rights reserved.