How to retrieve CancellationToken from http request on webApi?

Viewed 4613

I'm sending request to server like this via HttpClient:

public async Task GetTest()
{
    CancellationTokenSource tokenSource = new CancellationTokenSource();
    string url = String.Format($"api/Test/getTest");

    HttpResponseMessage response = await _httpClientFactory.HttpClient.GetAsync(url, tokenSource.Token).ConfigureAwait(false);

    response.EnsureSuccessStatusCode();
}

On WebApi (Core 2.1) method is like this:

[HttpGet("getTest")]
public async Task<IActionResult> GetTest(CancellationToken token)
{
    try
    {
        object test = await _dataService.GetTest(token);

        return Ok(test);
    }
    catch (Exception ex)
    {
        this._logger.LogError(ExceptionHelper.ExMessageDeepGet(ex));
        return new InternalServerErrorWithMessageResult(ex);
    }
}

In _dataService.GetTest(token) I do token.ThrowIfCancellationRequested();

Problem is that I get new token on webapi, not the one I've send via client so if I stop request (shut down client) before response from api, no exception is thrown..

Any suggestions?

1 Answers

Found soulution..

Actually we don't need to pass a cancellation token via the client, MVC does it automatically..

MVC will automatically bind any CancellationToken parameters in an action method to the HttpContext.RequestAborted token, using the CancellationTokenModelBinder. This model binder is registered automatically when you call services.AddMvc() (or services.AddMvcCore()) in Startup.ConfigureServices()

source: andrewlock.net

Related