Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API + Long running operation cancellation

Is there a way to figure out in ASP.NET Web API beta whether the HTTP request was cancelled (aborted by user of for any another reason)? I'm looking for opportunity to have a kind of cancellation token out-of-the-box that will signal that the request is aborted and therefore long-running ops should be aborted as well.

Possible related question - the use case for the CancellationTokenModelBinder class. What's the reason to have a separate binder for cancellation token?

like image 609
pavel.baravik Avatar asked Mar 18 '12 21:03

pavel.baravik


1 Answers

If you added CancellationToken in to controller methods, it will be automatically injected by the framework, and when a client calls xhr.abort() the token will be automatically cancelled

Something similar to

public Task<string> Get(CancellationToken cancellationToken = default(CancellationToken))

For MVC you can also refer to

HttpContext.Current.Response.IsClientConnected
HttpContext.Response.ClientDisconnectedToken

For .NetCore

services.AddTransient<ICustomInterface>(provider => { 
     var accessor = provider.GetService<IHttpContextAccessor>);
     accessor.HttpContext.RequestAborted;
  }); 
like image 80
Sameh Avatar answered Nov 13 '22 21:11

Sameh