title: How to cancel an upload
body: <p>I have a asp.net web api page where the user can upload some files. I am using <a href="https://github.com/blueimp/jQuery-File-Upload" rel="nofollow">jquery-file-upload</a>. Based on some condition, I want to cancel the upload from the server side but it is not working. No matter what I do, the file always goes to the server before asp.net returns the error. Example, I can keep just this when uploading:</p>
  
  <pre><code>public async Task&lt;HttpResponseMessage&gt; Post(int id, CancellationToken token)
  {
      return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Cant upload");
  }
  </code></pre>
  
  <p>If I put a breakpoint on the <code>return</code>, I can see that it is hitted as soon as the upload starts but I have to wait the upload to end and only then the javascript error handler gets called. Is it not possible to end the request imediatelly, cancelling the upload?</p>
  
  <p><strong>Update 1:</strong></p>
  
  <p>I replaced jquery-file-upload with jquery-form and now I am using ajaxSubmit on my form. This doen't changed anything.
  I also tried to implement a <code>DelegatingHandler</code>, like this:</p>
  
  <pre><code>public class TestErrorHandler : DelegatingHandler
  {
      protected async override Task&lt;HttpResponseMessage&gt; SendAsync(
          HttpRequestMessage request, CancellationToken cancellationToken)
      {
  
          //throw new HttpException(403, "You can't upload");
  
          var response = request.CreateResponse(HttpStatusCode.Unauthorized);
          response.ReasonPhrase = "You can't upload";
          return Task.FromResult&lt;HttpResponseMessage&gt;(response).Result;            
      }
  }
  
  config.MessageHandlers.Add(new TestErrorHandler());
  </code></pre>
  
  <p>That did not work either.</p>
  
  <p>And I tried to disable buffer on requests:</p>
  
  <pre><code>public class NoBufferPolicySelector : WebHostBufferPolicySelector
  {
      public override bool UseBufferedInputStream(object hostContext)
      {
          return false;   
      }        
  }
  
  config.Services.Replace(typeof(IHostBufferPolicySelector), new NoBufferPolicySelector());
  </code></pre>
  
  <p>No game - it still upload all the file before returning the error.</p>
  
  <p>All I need is to cancel a upload request. Is this impossible with web api or I am missing something here?</p>