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 Web APIs.
This is my first ever writing on ASP.NET Web APIs, so I’ll try my best to deliver what I learned about HTTP, REST, Web Services, Web API, and as well as asynchronous programming. As the article is about how to live stream videos with ASP.NET Web APIs, I still have to introduce other terminologies listed above for the folks who don’t already know about them. At the end, we will learn how we can set up a web service using ASP.NET Web APIs to live stream the videos asynchronously over HTTP protocol.
Background
I assume that you already have experience working with C# in ASP.NET (MVC, Web APIs) and generally know about how the Web works, about HTTP, about Servers and clients. You don’t need to be a master of them but you must have fair knowledge to follow along.
I’m also assuming that you have basic familiarity with working with Visual Studio. I’ll be using Visual Studio 2015 with Update 2 for this demo. If you are using Visual Studio 2013, then it’s perfectly fine.
ASP.NET Web APIs and REST
ASP.NET Web API is a new framework that Microsoft included in the ASP.NET family of technologies. Using ASP.NET Web APIs, we can create online Web Services or Web APIs, which client apps can consume to retrieve, update, and delete data over HTTP. Web services normally serve data in the form of JSON or XML.
The term API stands for Application Programming Interface, so whether someone says Web API or Web Service, it’s the same thing. Online Web Services have different names and formats like SOAP-based Services and most popular of them is REST or RESTful Services.
REST stands for Representational State Transfer. REST is an architectural pattern, that is used to create online Web Services to serve data in form of JSON and XML over HTTP protocol and that’s what exactly ASP.NET Web APIs are there for. Finally, we know we can create RESTful Services with ASP.NET Web APIs.
Asynchronous Programming
In asynchronous programming, we perform multiple tasks simultaneously parallel to each other at same time and the parallel running threads notify back to the calling thread after the completion of the task. In C# the best practice is to use TPL (Task Parallel Library) for parallel programming instead of using System.Threading.Thread. The task provides you with more control over threads.
If a task is not CPU bound but instead it's I/O bound or network bound where calling threads have to wait for database to respond or have to wait for a network call to respond, then we should use asynchronous pieces of code with async and await keywords. If you are not already familiar with asynchronous programming with Asyn and await, then click here to learn because Microsoft has made it very easy to write asynchronous code blocks with async and await for IO and Network tasks. Remember in IO or network-bound tasks thread remains idle to wait for a response, instead, why don’t we use them to perform some other tasks because we have limited resources?
Now, there is one question left in our minds: “What is Asynchronous Live streaming?”
What is Asynchronous video streaming?
In asynchronous video streaming, we send packets of data to the receiving client instead of sending the complete file and the client will be the browser in our case. For asynchronous live streaming with ASP.NET Web APIs, we will make use of the PushStreamContent class. The PushStreamContent class makes it possible to gradually send packets of data to the receiving client. With asynchronous streaming, we are reducing 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.
On the client side, we will use the HTML 5 video element to playback the received video content. As we are asynchronously delivering the video content 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 client will be requesting for data, the server will be serving the client and if the client disconnects, the streaming will be finished.
Demo
A lot more chit-chat... So now, let’s create a handy ASP.Net MVC app that can stream videos from the Server.
Remember, ASP.Net Web APIs are built from ASP.Net MVC, so the same conventions apply here too and you can also add a Web API controller inside an MVC project which is perfectly fine in ASP.Net 4.5. In fact, you can start from any ASP.NET project and later, you can add any component it from the ASP.NET family of technologies whether it's a Web API controller, MVC controller, Web form, or SignalR hub.
Create a new empty ASP.NET project with a folder structure selected as MVC and paste any sample video into the root directory of the project for demo purposes.

Right-click on the Controllers folder and add a new Web API 2 empty controller with any name. In my case, I’ll name it SampleController.

Now, first, we have to read the file from the server with FileStream so that we can write to the output stream. Now, we’ll create a new Helper method that can read the file and write its output stream. Paste the following code in SampleController which is not a good practice but we can do this for demo purposes.
public async void WriteContentToStream(Stream outputStream, HttpContent content, TransportContext transportContext)
{
// Path of the file we need to read
var filePath = HttpContext.Current.Server.MapPath("~/MicrosoftBizSparkWorksWithStartups.mp4");
// Set the size of the buffer (you can adjust this value)
int bufferSize = 1000;
byte[] buffer = new byte[bufferSize];
// Read the file from the server using FileStream
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
int totalSize = (int)fileStream.Length;
// Read bytes from the file as long as the total size is greater than 0
while (totalSize > 0)
{
int count = totalSize > bufferSize ? bufferSize : totalSize;
// Read the buffer from the original file
int sizeOfReadBuffer = fileStream.Read(buffer, 0, count);
// Write the read buffer to the output stream
await outputStream.WriteAsync(buffer, 0, sizeOfReadBuffer);
// Decrement the total size of the file
totalSize -= sizeOfReadBuffer;
}
}
}
Create a new action method with the name GetVideoContent. Again, I am assuming that you have basic familiarity with ASP.NET web APIs and know how routing works. In the GetVideoContent action, we will write the code that can gradually write our video's content returned from WriteContentToStream to HTTP response.
public HttpResponseMessage GetVideoContent()
{
var httpResponse = Request.CreateResponse();
httpResponse.Content = new PushStreamContent((Action<Stream, HttpContent, TransportContext>)WriteContentToStream);
return httpResponse;
}
Now, on the server side, the final thing left is to register a route so that we can call into our GetVideoContent action with the URL “API/Sample”.
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new
{
id = RouteParameter.Optional
}
);
}
Now, our Server is ready to serve the content on HTTP Get request at “API/Sample”. On the client side, all we need is an HTML 5 video element with src=” API/Sample”. Create a new HTML file and put the HTML 5 video element in it.

Now, right-click on the file and click view in the browser.

And finally, now you can see the playback.

I’m using my own media player but you can use the default controls for demo purposes and I’m assuming you know how to use HTML 5 controls.
SampleController.cs
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
namespace MediaPlayer.Controllers {
public class SampleController: ApiController {
public HttpResponseMessage GetVideoContent() {
var httpResponce = Request.CreateResponse();
httpResponce.Content = new PushStreamContent((Action<Stream, HttpContent, TransportContext>) WriteContentToStream);
return httpResponce;
}
public async void WriteContentToStream(Stream outputStream, HttpContent content, TransportContext transportContext) {
//path of file which we have to read//
var filePath = HttpContext.Current.Server.MapPath("~/MicrosoftBizSparkWorksWithStartups.mp4");
//here set the size of buffer, you can set any size
int bufferSize = 1000;
byte[] buffer = new byte[bufferSize];
//here we re using FileStream to read file from server//
using(var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
int totalSize = (int) fileStream.Length;
/*here we are saying read bytes from file as long as total size of file
is greater then 0*/
while (totalSize > 0) {
int count = totalSize > bufferSize ? bufferSize : totalSize;
//here we are reading the buffer from orginal file
int sizeOfReadedBuffer = fileStream.Read(buffer, 0, count);
//here we are writing the readed buffer to output//
await outputStream.WriteAsync(buffer, 0, sizeOfReadedBuffer);
//and finally after writing to output stream decrementing it to total size of file.
totalSize -= sizeOfReadedBuffer;
}
}
}
}
}
WebApiConfig.cs
using System.Web.Http;
namespace MediaPlayer
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new
{
id = RouteParameter.Optional
});
}
}
}

Sinclaire MboundaPosted Mar 22, 2022, 6:03 PM
Hello, i hope you'r fine. i try your code but i got HttpException The remote host closed the connection. The error code is 0x800703E3. I don't know why the rest of poeple didn't get it.
Yong KyPosted Mar 10, 2022, 7:05 AM
Hi thanks for sharing. please kindly share the source code to [email protected]
genco nonePosted Sep 6, 2021, 7:54 AM
Hello how can I access sourrce codes of project? Is it exist on github?
Alexander ReynaudPosted Jun 18, 2021, 11:34 AM
This is a great start, ty! But I'm noticing that while pasting the API link into an address bar results in the video being downloaded (albeit without the .mp4 at the end), the file can't ever seem to go through the <video> tag. Can I please have help on this? I've been looking everywhere and still haven't found an ASP solution that doesn't involve Azure. My email is [email protected]
Dev SinghPosted May 8, 2021, 7:01 PM
Great Job Shahed Ahmed, Can you share this project Code {[email protected]} or share me your GitHub repos. Please help me.
Dev SinghPosted May 8, 2021, 7:00 PM
Great Job Shahed Ahmed!!,
c yungPosted Mar 31, 2021, 10:35 PM
Hi Mobeen, very nice article. Can you please share the code at: [email protected]
Shahed AhmedPosted Feb 17, 2021, 10:15 AM
Hello,Very good job. Is there any Issue of big file size ? My file size is 39 MB . I able to upload this but its is not able to play at the client . Would you please let me know where is the issue , I didn't find any error message .
Pradel EugenePosted Jan 24, 2021, 9:12 PM
Hi Mobeen good Job. please, can you share me the code [email protected]
amrik puriPosted Jan 7, 2021, 3:31 AM
Hi Mobeen, very nice article. Can you please share the code at: [email protected]
Hakan KurtPosted Jan 4, 2021, 3:05 PM
Thank you for the information. Is that possible to share the code? if yes: [email protected] / thank you very much
Sumit RohilPosted Nov 25, 2020, 4:57 AM
Nice article, can you please share source code? if yes then please send on [email protected]
Md AftabPosted Aug 31, 2020, 1:33 PM
Nice Article, please could you share your source code with me? this is my email: [email protected]
Aprende aPosted Aug 23, 2020, 8:08 AM
In WriteContentToStream the loop must be do {....} while (totalSize > 0); if not on my test get a close server connection.
Krishna SaiPosted Jul 22, 2020, 12:42 PM
Could you please help me by sending source code to [email protected]
Fabian IfionuPosted Jul 9, 2020, 10:00 AM
Nice Article, please could you share your source code with me? this is my email: [email protected]
Alireza SadeghiPosted Jul 9, 2020, 3:48 AM
Hi, the video is playing well, but why can't I change player timeline go back and forth?
Vikas VikasPosted Apr 13, 2020, 12:28 PM
Bro we need live streaming using webcam not a video player we already do this thing 5 years ago video streaming movie website where one click play and one click download
Raghuram PerlaPosted Mar 16, 2020, 4:57 AM
Hi My video is not playing even after adding the controls . I have implemented exactly as mentioned in this article
Ahmed GaberPosted Jan 7, 2020, 5:25 PM
Nice article
Clement LeePosted Dec 26, 2019, 12:33 AM
Hi, my video is not playing
Taha TemuriPosted Dec 14, 2019, 5:38 PM
This is the best article I have ever seen on this site , great Mobeen
Gaurav SinhaPosted Oct 4, 2019, 11:49 PM
This is not live streaming (broadcast)
Lalo SanchezPosted Sep 27, 2019, 12:02 PM
Thanks for sharing, could you please send your code to [email protected]
Alberto GreenPosted Sep 12, 2019, 2:50 AM
Great! Could you please share your code to [email protected]
Khaled AlsaadiPosted Sep 7, 2019, 4:49 PM
Amazing, could you share your source code with me? This is my email: [email protected]
Memo LaraPosted Sep 4, 2019, 7:51 PM
Hi there! Excellent post, could you share your source code with me? This is my email: [email protected]
Piotr DevPosted Jul 10, 2019, 1:31 PM
Hi, could you share VS project on my email: [email protected], please? :) I will very appreciate that. Thank you
Arturo LedezmaPosted Jun 18, 2019, 1:11 PM
Nice article, can you please share the project with me, [email protected]
Raj KPosted May 24, 2019, 6:54 AM
Nice article, I did the same as you explained in the article. But the video is not playing, even I don't get any exceptions server side and client side, too. Can you please share the project with me, [email protected]
Ceyhun RehimovPosted May 17, 2019, 3:17 AM
Thanks for nice article. It does not work on asp.net core 2.1 version. Problem is on "var httpResponce = Request.CreateResponse();" part. Do you have a ASP.NET Core sample? if yes, please send me on [email protected].
Kawssar ChowdhuryPosted Apr 27, 2019, 11:54 PM
Please share the solution on [email protected] .... thanks for sharing your idea.
Long TrầnPosted Apr 21, 2019, 10:59 PM
Please share the complete visual studio solution file on [email protected]
Vicky SPosted Apr 10, 2019, 4:22 AM
Great article, can i have the code at [email protected] please.
liliana muñozPosted Apr 9, 2019, 5:26 PM
Please share the code to [email protected]
fahad siddiquiPosted Apr 3, 2019, 6:24 AM
Can you sher full source in [email protected]
Jose TepePosted Mar 29, 2019, 4:56 PM
Podria compartir las fuentes aqui ---> [email protected]
gopi karuppuswamyPosted Mar 20, 2019, 6:59 AM
Nice Article, Could you please share the source code to the following mail id "[email protected]"
imran qureshiPosted Mar 20, 2019, 2:46 AM
@Ahsan, can you please share the source at [email protected]
saji georgePosted Mar 6, 2019, 10:16 PM
Please share the code to [email protected]
saji georgePosted Feb 28, 2019, 4:12 AM
@Mobeen Rashid : Can we able to create Web API for video streaming from IP Live camera. I have RTSP url to get the video live and i want display into my web page.
saji georgePosted Feb 28, 2019, 3:58 AM
Please share the complete visual studio solution file on [email protected]
Rohit SPosted Feb 8, 2019, 6:30 AM
Please share the complete visual studio solution file on [email protected]
Rodrigo SouzaPosted Jan 24, 2019, 8:25 AM
Nice article! Can you share the source with me too? [email protected]. I need to put a water mark over the stream. Is it possible? Does anyone has an example? Thanks.
mas fassdfnPosted Jan 16, 2019, 5:55 PM
Can you sher full source in [email protected]
Ahsan SiddiquePosted Jan 2, 2019, 4:00 AM
https://www.strathweb.com/2013/01/asynchronously-streaming-video-with-asp-net-web-api/
Adward NguyenPosted Dec 21, 2018, 9:19 PM
How to set duration when streaming video? I want to set end of time 1:25 to 0:47. Please help to me!
Ragesh SPosted Oct 31, 2018, 3:31 AM
Thank you very much for your nice explanation. I have a error like below The remote host closed the connection. The error code is 0x80070040. and video player can't play the file.
Sourabh RautPosted Sep 30, 2018, 7:51 AM
Can you share full source code @[email protected]
Anbarasan SPosted Jul 17, 2018, 10:05 AM
I followed your guide but it doesnt work,plz send your sample project to my email .... [email protected]
Ashesh BallaPosted Jun 11, 2018, 3:05 AM
I have followed the steps but it did not work for me.can you please share me your code fully my email : [email protected]
Niket ShahPosted Jun 4, 2018, 5:43 AM
I followed your guide but it doesnt work,plz send your sample project to my email .... shah.niket16gmail.com
Dillon DhayanandanPosted Apr 18, 2018, 5:22 PM
Hi, Mobeen Rashid so i have checked that WriteContentToStream doesnt close the outputStream that was missed out on the code snippet .
Krishan KumarPosted Apr 11, 2018, 6:40 AM
Hi, Mobeen Rashid can we make multiple video stream continuously in one source like if I have two or three videos then I want to play these videos back to back asynchronously in one source.
Karan EkkawalaPosted Mar 20, 2018, 6:48 AM
I am getting this error because of my file size is to big , how can i resolved this issue .
vilas jadhavPosted Mar 13, 2018, 12:23 PM
How can i get 1000000 records from sql server to mvc view html table with pagination using rest api same logic , without getting all at one time, how can i made straming for this
morteza zandPosted Feb 24, 2018, 4:15 AM
I followed your guide but it doesnt work,plz send your sample project to my email .... [email protected] .tnx
Tu VietPosted Jan 31, 2018, 12:38 AM
I followed your guide but it doesnt work, may I have the source code please? Send me via email address [email protected]. Thank you in advance
सागर जुंदरेPosted Jan 25, 2018, 5:04 AM
Plz share this code .... my email id is [email protected]
hieuPosted Jan 15, 2018, 2:26 AM
Can you share this demo code for me? I'm tried, but have some wrong. I'm really not good with web API. Anything start at "0" point. Please send this code to my email "[email protected]". Hope reply from you and thank you so much.
Shreekumar SPosted Jul 10, 2017, 9:30 AM
It's taking usual time (downloading whole file) on remote server. In localhost, it's working as expected. Anything need to set in IIS?
NathanPosted Apr 5, 2017, 9:39 PM
Hi, this is great article and it's applicable for light streaming but definitely not scalable. Firstly, it doesn't support adaptive streaming and secondly it doesn't utilise CDN. Having this solution on a single server will definitely drain CPU resources.
farooq smdPosted Feb 17, 2017, 6:55 AM
Code please [email protected]
Former memberPosted Jan 12, 2017, 4:03 AM
Thanks for this article. can you please post a source code in zip file format so we all can download and run your code in our pc just to see how it is working. thanks
Nigel FernandesPosted Jan 11, 2017, 8:34 PM
Very useful article , I will be trying this in my website. .. THanks
Mobeen RashidPosted Jan 11, 2017, 12:08 PM
Let me know Sir Mahesh Chand if I was of some help
Mahesh ChandPosted Jan 11, 2017, 9:40 AM
Great. What kind of delay if you have noticed any? Any performance? What do we need from hardware/Internet or any other requirements? We need to figure out a build live streaming Video on C# Corner website.