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?
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With