Azure Functions using Cancellation Token with Http Trigger
I know this is an old question, but I found the answer to this issue.
In Azure Functions, there are 2 cancellation tokens.
The token passed in Function Method parameter is the Host Cancellation Token - cancellation is requested when the host is about to shut down.
The other token is req.HttpContext.RequestAborted
property. It's being cancelled when browser cancels the request - this is what you were after.
In addition, you can use following code:
using var cancellationSource = CancellationTokenSource.CreateLinkedTokenSource(hostCancellationToken, req.HttpContext.RequestAborted);
To get a token that cancels when either host or request is being cancelled.
Without using Durable Functions, I don't think it's possible. Here's a sample using Durable:
[FunctionName("ApprovalWorkflow")]public static async Task Run( [OrchestrationTrigger] IDurableOrchestrationContext context){ await context.CallActivityAsync("RequestApproval", null); using (var timeoutCts = new CancellationTokenSource()) { DateTime dueTime = context.CurrentUtcDateTime.AddHours(72); Task durableTimeout = context.CreateTimer(dueTime, timeoutCts.Token); Task<bool> approvalEvent = context.WaitForExternalEvent<bool>("ApprovalEvent"); if (approvalEvent == await Task.WhenAny(approvalEvent, durableTimeout)) { timeoutCts.Cancel(); await context.CallActivityAsync("ProcessApproval", approvalEvent.Result); } else { await context.CallActivityAsync("Escalate", null); } }}