Here is the solution I used to create a Web API Controller in C# (MVC) that will serve video files with Byte Ranges (partial requests). Partial requests allow a browser to only download as much of the video as it needs to play rather than downloading the entire video. This makes it far more efficient.
Note this only works in recent versions.
var stream = new FileStream(videoFilename, FileMode.Open, FileAccess.Read , FileShare.Read);
var mediaType = MediaTypeHeaderValue.Parse($"video/{videoFormat}");
if (Request.Headers.Range != null)
{
try
{
var partialResponse = Request.CreateResponse(HttpStatusCode.PartialContent);
partialResponse.Content = new ByteRangeStreamContent(stream, Request.Headers.Range, mediaType);
return partialResponse;
}
catch (InvalidByteRangeException invalidByteRangeException)
{
return Request.CreateErrorResponse(invalidByteRangeException);
}
}
else
{
// If it is not a range request we just send the whole thing as normal
var fullResponse = Request.CreateResponse(HttpStatusCode.OK);
fullResponse.Content = new StreamContent(stream);
fullResponse.Content.Headers.ContentType = mediaType;
return fullResponse;
}