title: Authenticate Web API session before body upload
body: <p>I have a simple Web API 2 controller that handles file uploads. It looks like this:</p>
  
  <pre><code>[MyCustomAuthenticationFilter]
  [Authorize]
  public class FileController : ApiController
  {
      private IFileRepository _FileRepository;
  
      public FileController(IFileRepository fileRepository)
      {
          _FileRepository = fileRepository;
      }
  
      public async Task&lt;FileInfo&gt; Post()
      {
          var stream = await Request.Content.ReadAsStreamAsync();            
          var info = await _FileRepository.CreateFileAsync(stream);
  
          return new FileInfo(info);
      }
  }
  </code></pre>
  
  <p>It takes a streamed upload from the client, hands it off to a repository object (which talks to an Azure Storage Blob container), and then returns some data about the uploaded file. Simple enough, and it works great.</p>
  
  <p>Except, the authentication filter is not applied until the client has finished uploading the file. Authentication is a simple challenge/response system using a token, so this means a client could easily upload several hundred megabytes of data (potentially over a slow cellular data connection) before finding out that their token has expired and they need to refresh it and try again. I'd like to be able to examine the request header and validate (or reject) it as early as possible, but that doesn't seem to be doable with the standard filters. I also tried creating a simple <code>IHttpModule</code> and hooking into the <code>BeginRequest</code> event, but that apparently does not fire until after the upload completes, either.</p>
  
  <p>How can I hook into the pipeline such that I can validate the Authorization headers for a request before the client upload completes?</p>
  
  <p><strong>Edit to add:</strong>
  Obviously Authenticating early doesn't do me any good if I can't also Authorize, based on the route in Web API. My service has a few anonymous methods, so I can't just blanket reject un-authenticated users. Given the architecture of IIS and ASP.net, maybe that means this just isn't possible.</p>