Asynchronous Live Video Streaming Web API In .NET Core 3.1

In this article we will learn how we can live stream our video content over HTTP, using Web APIs. No matter what kind of project you are working on, at some point you will find the requirement to stream videos on your website or mobile apps or for some other purposes.

What Is Asynchronous Video Streaming?

In asynchronous video streaming, we send packets of data to the receiver client instead of sending the complete file and the client will be the browser. For asynchronous live streaming with ASP.NET Web APIs, we will make use of FileStream class. It helps us to make it possible to gradually send packets of data to the receiving client. With the help of asynchronous streaming, we can reduce the load on the server-side so that the Server doesn’t have to serve the whole file at a time, instead, it can serve it with a specific size of packets.

Let us understand with the help of an example.

Prerequisites

In our demo on the client-side, we will use HTML 5 video element to playback the received video content. As we are delivering the video content asynchronously to the client, we don’t have to wait for the whole file to be downloaded. The playback will be immediately started. As long as the client will be requesting data, the server will be serving the client and if the client disconnects, the streaming will be finished.

First, open Visual Studio 2019 and create a Web API application.

Here is the project structure of my demo project.

First, create VideoController.cs and add the following code to it.

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;

namespace LiveStreammingDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class VideoController : ControllerBase
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        public VideoController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        [HttpGet("GetVideoContent")]
        public async Task<IActionResult> GetVideoContent(string fileName)
        {
            string path = Path.Combine(_hostingEnvironment.WebRootPath, "Video/") + fileName;
            var memory = new MemoryStream();
            using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 65536, FileOptions.Asynchronous | FileOptions.SequentialScan))
            {
                await stream.CopyToAsync(memory);
            }
            memory.Position = 0;
            return File(memory, "application/octet-stream", Path.GetFileName(path), true); //enableRangeProcessing = true
        }
    }
}

Add the following line in Startup.cs under the Configure method.

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
       if (env.IsDevelopment())
       {
           app.UseDeveloperExceptionPage();
       }
       app.UseHttpsRedirection();
       app.UseRouting();
       app.UseDefaultFiles();
       app.UseAuthorization();
       app.UseEndpoints(endpoints =>
       {
           endpoints.MapControllers();
       });
}

Just add the Media.html file in your project and call your GetVideoContent API from it.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <video width="480" height="320" controls="controls" autoplay="autoplay">
        <source src="https://localhost:44389/Video/GetVideoContent?fileName=Doraemon.mp4" type="video/mp4">
    </video>
</body>
</html>

That’s It.

To run it right-click on your Media.html file and select View in Browser (Google Chrome)

And finally, now you can see the playback.

Also, Check How To Add Google Authentication In .Net 5.0

1 Comment

  1. ali shakkouf

    It throws ‘stream.ReadTimeout’ threw an exception of type ‘System.InvalidOperationException’

    0
    0
    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories