Custom ASP.NET Core Middleware with cancellation Token
Asked Answered
S

2

20

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?

Secor answered 29/6, 2016 at 11:43 Comment(0)
P
37

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

Petrillo answered 29/6, 2016 at 12:3 Comment(2)
I agree, but please note: CancellationToken is a struct, and HttpContext.RequestAborted is not a nullable, so will never be null. Therefore the null-coalescing operator (??) is not appropriate and will not compile.Buzzard
The null check is because of context?. so it can be null in the case context is null.Saari
M
1

Also you can catch it in case of operation cancel inside your exception handling middleware like this:

catch(OperationCanceledException ex) when (ex.CancellationToken == context.RequestAborted) { // log here}
Macbeth answered 26/9, 2023 at 10:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.