Streaming video asynchronously in ASP.NET Core 2 with Web API

 

Introduction

No matter what kind of project you are working on, at some point you will find the need to stream videos in your website or mobile apps for many purposes. So, we will learn how we can live stream our video content over HTTP, using ASP.NET Core 2 Web APIs.

Set up a service that get a Stream from a video hosted in the web using HttpClient

Example with videos hosted in Azure:

public class AzureVideoStreamService : IAzureVideoStreamService
{
   private HttpClient _client;

   public AzureVideoStreamService()
   {
      _client = new HttpClient();
   }

   public async Task<Stream> GetVideoByName(string name)
   {
      var urlBlob = string.Empty;
      switch (name)
      {
         case "earth":
         urlBlob = "https://anthonygiretti.blob.core.windows.net/videos/earth.mp4";
         break;
         case "nature1":
         urlBlob = "https://anthonygiretti.blob.core.windows.net/videos/nature1.mp4";
         break;
         case "nature2":
         default:
         urlBlob = "https://anthonygiretti.blob.core.windows.net/videos/nature2.mp4";
         break;
      }
      return await _client.GetStreamAsync(urlBlob);
   }

   ~AzureVideoStreamService()
   {
      if (_client != null)
      _client.Dispose();
   }
}
public interface IAzureVideoStreamService
{
   Task<Stream> GetVideoByName(string name);
}

Then don’t forget to register the service and it’s interface in Injection Dependency system

public void ConfigureServices(IServiceCollection services)
{
   services.AddMvc();
   services.AddScoped<IAzureVideoStreamService, AzureVideoStreamService>();
}

Set up a Streaming controller that stream videos using FileStreamResult object

FileStreamResult sends binary content to the response using a Stream instance

Example of an API that return a video by its name:

[Route("api/[controller]")]
public class StreamingController : Controller
{
   private IAzureVideoStreamService _streamingService;

   public StreamingController(IAzureVideoStreamService streamingService)
   {
      _streamingService = streamingService;
   }

   [HttpGet("{name}")]
   public async Task<FileStreamResult> Get(string name)
   {
      var stream = await _streamingService.GetVideoByName(name);
      return new FileStreamResult(stream, "video/mp4");
   }
}

Run the Web API to test….

 

 

Easy isn’t it ? 😉