Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom ASP.NET Core Middleware with cancellation Token

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?

like image 524
Boas Enkler Avatar asked Jun 29 '16 11:06

Boas Enkler


People also ask

What is cancellation token in ASP.NET Core?

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.

What is custom middleware in ASP.NET Core?

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.

What is IApplicationBuilder in .NET Core?

IApplicationBuilder An object that provides the mechanisms to configure an application's request pipeline.


1 Answers

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

like image 94
Joe Audette Avatar answered Sep 18 '22 02:09

Joe Audette