Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在webApi上从http请求中检索CancellationToken?_C#_Asp.net Core_Asp.net Core Webapi_Dotnet Httpclient_Asp.net Core 2.1 - Fatal编程技术网

C# 如何在webApi上从http请求中检索CancellationToken?

C# 如何在webApi上从http请求中检索CancellationToken?,c#,asp.net-core,asp.net-core-webapi,dotnet-httpclient,asp.net-core-2.1,C#,Asp.net Core,Asp.net Core Webapi,Dotnet Httpclient,Asp.net Core 2.1,我通过HttpClient向服务器发送如下请求: public async Task GetTest() { CancellationTokenSource tokenSource = new CancellationTokenSource(); string url = String.Format($"api/Test/getTest"); HttpResponseMessage response = await _httpClientFactory.HttpClie

我通过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();
}
在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);
    }
}
[HttpGet(“getTest”)]
公共异步任务GetTest(CancellationToken令牌)
{
尝试
{
对象测试=等待dataService.GetTest(令牌);
返回Ok(测试);
}
捕获(例外情况除外)
{
此.u logger.LogError(ExceptionHelper.ExMessageDeepGet(ex));
返回新的InternalServerErrorWithMessageResult(ex);
}
}
\u dataService.GetTest(token)
I do
token.ThrowIfCancellationRequested()

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

有什么建议吗?

找到了解决方案

实际上,我们不需要通过客户端传递取消令牌,MVC会自动传递

MVC将使用CancellationTokenModelBinder自动将操作方法中的任何CancellationToken参数绑定到HttpContext.RequestAborted令牌。在Startup.ConfigureServices()中调用services.AddMvc()(或services.AddMvcCore())时,会自动注册此模型绑定器

资料来源: