小编Nen*_*nad的帖子

如何从 webApi 上的 http 请求中检索 CancellationToken?

我通过 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();
}
Run Code Online (Sandbox Code Playgroud)

在WebApi(Core 2.1)上方法是这样的:

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)

_dataService.GetTest(token)我做token.ThrowIfCancellationRequested();

问题是我在 webapi 上获得了新令牌,而不是通过客户端发送的令牌,因此如果我在 api 响应之前停止请求(关闭客户端),则不会引发异常。

有什么建议么?

c# dotnet-httpclient asp.net-core asp.net-core-webapi asp.net-core-2.1

5
推荐指数
1
解决办法
6255
查看次数