I am newbi in using Video streaming in ASP.Net MVC project. I have a video library webpplication, most of the videos are .mp4
format. Please see my code below.
Code
public HttpResponseMessage Get(string filename)
{
var filePath = new FileStreameHelpers().GetFilePath(filename);
if (!File.Exists(filePath))
return new HttpResponseMessage(HttpStatusCode.NotFound);
var response = Request.CreateResponse();
response.Headers.AcceptRanges.Add("bytes");
var streamer = new FileStreameHelpers();
streamer.FileInfo = new FileInfo(filePath);
response.Content = new PushStreamContent(streamer.WriteToStream, new FileStreameHelpers().GetMimeType(Path.GetExtension(filePath)));
RangeHeaderValue rangeHeader = Request.Headers.Range;
if (rangeHeader != null)
{
long totalLength = streamer.FileInfo.Length;
var range = rangeHeader.Ranges.First();
streamer.Start = range.From ?? 0;
streamer.End = range.To ?? totalLength - 1;
response.Content.Headers.ContentLength = streamer.End - streamer.Start + 1;
response.Content.Headers.ContentRange = new ContentRangeHeaderValue(streamer.Start, streamer.End,
totalLength);
response.StatusCode = HttpStatusCode.PartialContent;
}
else
{
response.StatusCode = HttpStatusCode.OK;
}
return response;
}
public async Task WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
{
try
{
var buffer = new byte[6553600];
using (var video = FileInfo.OpenRead())
{
if (End == -1)
{
End = video.Length;
}
var position = Start;
var bytesLeft = End - Start + 1;
video.Position = Start;
while (position <= End)
{
var bytesRead = video.Read(buffer, 0, (int)Math.Min(bytesLeft, buffer.Length));
await outputStream.WriteAsync(buffer, 0, bytesRead);
position += bytesRead;
bytesLeft = End - position + 1;
}
}
}
catch (Exception ex)
{
// fail silently
Utilities.SaveException("FileStreameHelpers - WriteToStream", ex);
}
finally
{
outputStream.Close();
}
}
it works fine in Firefox and Chrome but it shows error in Microsoft Edge browser like below.
HTML
<video width="320" height="240" controls>
<source src="/api/Media/Get?filename=SampleVideo_1280x720_1mb.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
The remote host closed the connection. The error code is 0x800703E3.
Please advice.
Actually it's a browser related issue. I update my MS Edge browser. now the video streaming works correctly.
User contributions licensed under CC BY-SA 3.0