Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CancellationToken not working in asp.net core

I'm using Asp.net Core API and set services like bellow:

services
    .Configure<AppOptions>(_configuration.GetSection("app"))
    .AddMvcCore(options =>
        {
            options.RespectBrowserAcceptHeader = true;
            options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
            options.InputFormatters.Add(new XmlSerializerInputFormatter(options));
        })
    .AddFormatterMappings()
    .AddJsonFormatters()
    .AddXmlSerializerFormatters()
    .AddCors();

After that, I created an API with a CancellationToken parameter like this:

[HttpGet("list")]
public async Task<ActionResult<IEnumerable<string>>> Get(CancellationToken cancellationToken)
{
    var result = await _orderBusinessService.GetList(cancellationToken);

    return Ok(result);
}

When I call this API from Postman or browser I getting below response:

415 Unsupported Media Type

When I added [FromQuery] to cancellationToken, It's OK.

Actually, that seems CancellationTokenModelBinder not working.

I don't know why? Has anybody any ideas?

like image 884
Saeid Mirzaei Avatar asked Aug 05 '19 10:08

Saeid Mirzaei


People also ask

What is CancellationToken in asp net core?

So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan. Here we are going to see some sample code snippets about implementing a CancellationToken for Entity FrameworkCore, Dapper ORM, and HttpClient calls in Asp. NetCore MVC application.

How does C# CancellationToken work?

A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource. Token property.

Can you reuse CancellationToken?

Yes, you can reuse CancellationTokens. A CancellationTokenSource is used to cancel a set of processes. All processes associated with a particular CancellationTokenSource will use one CancellationToken among them.

Should I use CancellationToken?

Whether you're doing async work or not, accepting a CancellationToken as a parameter to your method is a great pattern for allowing your caller to express lost interest in the result. Supporting cancelable operations comes with a little bit of extra responsibility on your part.


1 Answers

Please check your Startup class, and make sure you have the compatibility version set:

services.AddMvcCore()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .AddApiExplorer()
    .AddAuthorization();

Adding that one line fixed the issue for me. (See https://github.com/microsoft/aspnet-api-versioning/issues/534#issuecomment-521680394 for the comment that pushed me in the right direction).

like image 125
David Keaveny Avatar answered Oct 22 '22 01:10

David Keaveny