Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect an aborted request in ASP.NET MVC

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();
}
like image 587
jdknezek Avatar asked Feb 10 '11 22:02

jdknezek


2 Answers

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.

like image 114
Will D Avatar answered Oct 04 '22 19:10

Will D


Try

CancellationToken clientDisconnectedToken = HttpContext.Response.ClientDisconnectedToken;
like image 43
Peter Punzenberger Avatar answered Oct 04 '22 18:10

Peter Punzenberger