We can pass Cancellation token in GraphQL’s endpoint using IHttpContextAccessor.

In the below example we are injecting IHttpContextAccessor in GetAccountQuery class’s constructor, and then accessing cancellation taken as ‘accessor.HttpContext.RequestAborted’ and then passing it into GraphQL’s endpoint.

public class GetAccountQuery : ObjectGraphType
{
    public GetAccountQuery(IResolver resolver, IHttpContextAccessor accessor)
    {
        FieldAsync<UserType>(
            "GetAccount",
            arguments: new QueryArguments(  
                new QueryArgument<NonNullGraphType<IdGraphType>> { Name = "userId" }),
            resolve: async context =>
            {
                var cancellationToken = accessor.HttpContext.RequestAborted; // Get cancellation token from the context
                return await resolver.ResolveAsync(context, cancellationToken);
            });
    }
}

Make sure you have registered ‘IHttpContextAccessor’ in the Program.cs file using below line of code:

builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Need Help With .Net Development?

Work with our skilled .Net developers to accelerate your project and boost its performance.

Hire .Net Developers

Support On Demand!

Related Q&A