title: Streaming a video in chunks to the client
body: <p><em>Info: (HTTP/2) Kestrel hosted Blazor WASM ASP.NET Core 6 preview 1 / C# 9 Project.</em></p>
  <p>I've written the code below to stream a video file in (actual physical) separate chunks from the server to the client, to prevent the average user to download the video in one click in (for example) the browser's DevTools.</p>
  <p>It actually works (<em>see the screenshot below the code snippets</em>) and seeking works as well, but I'm wondering if I'm doing this right. I hope I can use SO for this, but I'm actually looking for help, advise and/or comments on my code. I've been working on this code block for the past 2 weeks, searching for code snippets, reading docs/blogs and now I finally have something that works but maybe I'm doing this wrong or maybe I'm forgetting something really important. Does this code scale is one of my questions. Am I using the <code>using</code> declarations correctly. Does the code looks okay anyways :)</p>
  <p>FYI: I know about the <code>enableRangeProcessing</code> parameter, but AFAIK that isn't applicable in this case. And seeking does work.</p>
  <p><em>/Server/Controllers/StreamController.cs</em></p>
  <pre><code>using Microsoft.AspNetCore.Hosting;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.Extensions.FileProviders;
  using Microsoft.Extensions.Logging;
  using System;
  using System.IO;
  using System.Threading.Tasks;
  
  namespace Media.Server.Controllers
  {
      [Route(&quot;[controller]&quot;)]
      public class StreamController : ControllerBase
      {
          private readonly IWebHostEnvironment env;
          private readonly ILogger&lt;StreamController&gt; logger;
          public StreamController(ILogger&lt;StreamController&gt; logger, IWebHostEnvironment env)
          {
              this.logger = logger;
              this.env = env;
          }
  
          [HttpGet(&quot;{file}&quot;)]
          public async Task GetStream(string file)
          {
              var provider = new PhysicalFileProvider(env.ContentRootPath);
              string videoPathFile = Path.Combine(provider.Root, &quot;Files&quot;, &quot;Videos&quot;, $&quot;{file}&quot;);
              byte[] buffer = new byte[1024 * 1024 * 4]; // 'Chunks' of 4MB
              long startPosition = 0;
  
              if (!string.IsNullOrEmpty(Request.Headers[&quot;Range&quot;]))
              {
                  string[] range = Request.Headers[&quot;Range&quot;].ToString().Split(new char[] { '=', '-' });
                  startPosition = long.Parse(range[1]);
              }
  
              using FileStream inputStream = new(videoPathFile, FileMode.Open, FileAccess.Read, FileShare.Read)
              {
                  Position = startPosition
              };
              int chunkSize = await inputStream.ReadAsync(buffer.AsMemory(0, buffer.Length));
              long fileSize = inputStream.Length;
  
              if (chunkSize &gt; 0)
              {
                  Response.StatusCode = 206;
                  Response.Headers[&quot;Accept-Ranges&quot;] = &quot;bytes&quot;;
                  Response.Headers[&quot;Content-Range&quot;] = string.Format($&quot; bytes {startPosition}-{fileSize - 1}/{fileSize}&quot;);
                  Response.ContentType = &quot;application/octet-stream&quot;;
  
                  using Stream outputStream = Response.Body;
                  await outputStream.WriteAsync(buffer.AsMemory(0, chunkSize));
              };
          }
      }
  }
  </code></pre>
  <p><em>(part of) client side <code>.razor</code> code</em></p>
  <pre><code>&lt;video id=&quot;videostream&quot; poster=&quot;@videoPoster&quot; class=&quot;videostyle&quot; oncontextmenu=&quot;return false;&quot; controls disablePictureInPicture controlsList=&quot;nodownload&quot;&gt;
      &lt;source src=&quot;/Stream/@videoFileName&quot; type=&quot;@ContentType;codecs=@Codecs&quot; /&gt;
      Your browser does not support the video tag.
  &lt;/video&gt;
  </code></pre>
  <p><em>Screenshot of DevTools network pane</em></p>
  <p><a href="https://i.stack.imgur.com/nK2yw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nK2yw.jpg" alt="DevTools Screenshot" /></a></p>