简体   繁体   中英

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?

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).

In my case I was trying to use constructor injection instead of method. Removing it from the constructor and adding it as a parameter on the actions fixed it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM