Search code examples
asp.net-core-2.0filestreammemorystream

Streaming video files in asp.net core 2


I want to play video in browser using asp.net core

in html I have

<video width="320" height="240" controls>
 <source src="http://localhost:55193/api/VideoPlayer/Download" type="video/mp4">
 Your browser does not support the video tag.
</video>

and in asp.net core 2

    [HttpGet]
    [Route("Download")]
    public async Task<IActionResult> Download()
    {
        var path = @"d:\test\somemovie.mp4";
        var memory = new MemoryStream();
        using (var stream = new FileStream(@"d:\test\somemovie.mp4", 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));
    }

Does this code play file by streaming( I mean buffer file chunk by chunk and play)?

And if I want to play file from any position which user set the player's progress, How I can do it?


Solution

  • Just use the normal return PhysicalFile here:

    public class HomeController : Controller
        {
            public IActionResult Download()
            {
                return PhysicalFile(@"d:\test\somemovie.mp4", "application/octet-stream");
            }
    

    Because it supports range headers which are necessary for streaming and resuming a file download: enter image description here

    Also return File, FileStreamResult and VirtualFileResult support partial range requests too. Even static files middleware supports that too.