Idiomatic way to access CancellationToken in async Service methods?

What’s the recommended way to get a CancellationToken inside a regular HTTP service method?

Am I allowed to simply add it as a method parameter?

I’ve found a few options in the source but I’m not sure which is the intended approach for HTTP requests:

  1. Request.GetCancellationToken() (from JobUtils.cs) - but SetCancellationToken is only called from BackgroundJobs, so this returns CancellationToken.None for regular HTTP requests.
  2. CancellableRequestsFeature - requires the client to send an X-Tag header and explicitly call a cancel endpoint. This seems designed for a specific use case rather than general-purpose cancellation.
  3. Casting to NetCoreRequest to access HttpContext.RequestAborted:
       public async Task Any(MyRequest request)
       {
          var token = ((NetCoreRequest)Request).HttpContext.RequestAborted;
          await SomeDatabaseQuery(token);
       }
    
    This works but feels like it’s reaching outside ServiceStack’s abstraction.

Is there a built-in way I’m missing to access a cancellation token that’s tied to the HTTP connection lifetime? Would it make sense for ServiceStack to surface HttpContext.RequestAborted through IRequest (or populate Request.Items[“CancellationToken”] for HTTP requests the same way Background Jobs does)?

Thanks!

It’s not exposed as there’s no equivalent in most other Host Abstractions but 3) would be the way to access it in .NET Applications which I’d wrap behind an extension method if you use it frequently.

But I’ve just added an abstraction for in this commit.

Which you’ll be able to access with Request.RequestAborted

This change is available from the latest 10.0.7+ which is now available in the pre-release packages