We have a .NET 7 application running on Windows Server with IIS that returns feeds from cameras to a front end but the returned stream is very stuttery compared to the original output viewed in chrome on the server.
Is there any additional changes that could be made in the code or config in IIS that could make it run smoother?
Watching the stream from the original camera URLs in chrome on the server works smoothly so it seems like an issue in .NET handling the stream.
This is how we have it returning so far:
[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);
}
This is then consumed on the frontend using an img
<img src="/api/camera/1" />
Figured out a possible answer, at the beginning of the Get request, I use the DisableBuffering
method in HttpContext
features and now the returned stream is smooth with no latency/buffering.
Not sure if this is the best approach or the right place to put it but it has solved the issue.
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);
}