Async video streaming in ASP.Net Core Web Api is not working Async video streaming in ASP.Net Core Web Api is not working asp.net asp.net

Async video streaming in ASP.Net Core Web Api is not working


Looking at the source code for Asp.NET Core really helped me find the answer to this one. They have a StreamOutputFormatter class that's really close to what you want to use. I only had to modify it to look for PushStreamContent and it worked like a charm.

Here's my complete VideoOutputFormatter:

public class VideoOutputFormatter : IOutputFormatter{    public bool CanWriteResult(OutputFormatterCanWriteContext context)    {        if (context == null)            throw new ArgumentNullException(nameof(context));        if (context.Object is PushStreamContent)            return true;        return false;    }    public async Task WriteAsync(OutputFormatterWriteContext context)    {        if (context == null)            throw new ArgumentNullException(nameof(context));        using (var stream = ((PushStreamContent)context.Object))        {            var response = context.HttpContext.Response;            if (context.ContentType != null)            {                response.ContentType = context.ContentType.ToString();            }            await stream.CopyToAsync(response.Body);        }    }}

Instead of wrapping the HttpResponseMessage in the ObjectResult in your controller, you'll want to just shove the PushStreamContent object into the ObjectResult instead. You still need to set the MediaTypeHeaderValue on the ObjectResult.