Created
January 9, 2020 21:03
-
-
Save mustafamagdy/a646a94d9884e9caf6ccd32e0f7755a0 to your computer and use it in GitHub Desktop.
stream video using .net core web API source -> https://www.strathweb.com/2013/01/asynchronously-streaming-video-with-asp-net-web-api/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class VideoStream | |
| { | |
| private readonly string _filename; | |
| public VideoStream(string filename, string ext) | |
| { | |
| _filename = @"C:UsersFilipDownloads" + filename + "."+ext; | |
| } | |
| public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context) | |
| { | |
| try | |
| { | |
| var buffer = new byte[65536]; | |
| using (var video = File.Open(_filename, FileMode.Open, FileAccess.Read)) | |
| { | |
| var length = (int)video.Length; | |
| var bytesRead = 1; | |
| while (length > 0 && bytesRead > 0) | |
| { | |
| bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length)); | |
| await outputStream.WriteAsync(buffer, 0, bytesRead); | |
| length -= bytesRead; | |
| } | |
| } | |
| } | |
| catch (HttpException ex) | |
| { | |
| return; | |
| } | |
| finally | |
| { | |
| outputStream.Close(); | |
| } | |
| } | |
| } | |
| public class VideosController : ApiController | |
| { | |
| public HttpResponseMessage Get(string filename, string ext) | |
| { | |
| var video = new VideoStream(filename, ext); | |
| var response = Request.CreateResponse(); | |
| response.Content = new PushStreamContent(video.WriteToStream, new MediaTypeHeaderValue("video/"+ext)); | |
| return response; | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment