8

In an async controller in ASP.NET MVC, is there any way to tell if/when the request is aborted by the client?

[NoAsyncTimeout]
public void IndexAsync() {
  var source = new CancellationTokenSource();

  Task.Factory.StartNew(() => {
    while (true) {
      if (source.Token.IsCancellationRequested) {
        AsyncManager.Finish();
        return;
      }

      Response.Write(".");
      Thread.Sleep(1000);
    }
  }, source.Token);

  // Is there any way to do this?
  Request.Aborted += (sender, e) => source.Cancel();

  AsyncManager.OutstandingOperations.Increment();
}
jdknezek
  • 81
  • 1
  • 3
  • 1
    possible duplicate of [Detecting async client disconnect in ASP.NET MVC](http://stackoverflow.com/questions/4772597/detecting-async-client-disconnect-in-asp-net-mvc) I just found this too, it answers your question as well with some other information. – Filip Ekberg Feb 10 '11 at 22:08

2 Answers2

9

What about using

HttpContext.Current.Response.IsClientConnected

From a very basic test this doesn't seem to work for aborted ajax requests. MSDN suggests that it should though.

Will D
  • 844
  • 10
  • 12
  • I'm using it in Sync contexts inside while loops, and it works perfectly, allowing to dispose of processes, streams or cached files before ending a response. – Léon Pelletier Oct 05 '12 at 07:13
  • I find that it does work for aborted AJAX requests, but not when Fiddler's monitoring what's going on! I use Fiddler almost all the time, so it took a while to spot that. I'm using jQuery. I say `var myRequest = $.post(...);`, followed shortly afterwards by `myRequest.abort();` – teedyay Oct 07 '14 at 11:19
4

Try

CancellationToken clientDisconnectedToken = HttpContext.Response.ClientDisconnectedToken;