I have a custom ASP.NET Core middleware and I want to retrieve the cancellation token for the request.
I tried to add it to the signature of the invoke like this:
public async Task Invoke(HttpContext context,CancellationToken token)
But as soon as I add it, it isn't called any more.
What am I doing wrong?
Long running requests in ASP.NET Core Cancellation tokens should also be passed to other internal operations. Eventually, the object that created the long running operations may — after a time deadline is reached, or when a user stops a request — propagate a cancellation notification to these cancellation tokens.
The custom middleware component is like any other . NET class with Invoke() method. However, in order to execute next middleware in a sequence, it should have RequestDelegate type parameter in the constructor. Visual Studio includes template for creating standard middleware class.
IApplicationBuilder An object that provides the mechanisms to configure an application's request pipeline.
I think the idea is not to be able to cancel invocation of the middleware, from inside the middleware if you call some async task that accepts a cancellation token then you can create one and pass it in to what you are calling from inside there.
A common scenario would be to cancel a task if the request is aborted, so you could create the token like this:
CancellationToken CancellationToken => context?.RequestAborted ?? CancellationToken.None;
and then call some async service like getting data or querying the db, if the request is aborted then the cancellation request should happen
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With