Nen*_*nad 5 c# dotnet-httpclient asp.net-core asp.net-core-webapi 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.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 响应之前停止请求(关闭客户端),则不会引发异常。
有什么建议么?
找到解决方案..
实际上我们不需要通过客户端传递取消令牌,MVC 会自动完成。
MVC 将使用 CancellationTokenModelBinder 自动将操作方法中的任何 CancellationToken 参数绑定到 HttpContext.RequestAborted 令牌。当您在 Startup.ConfigureServices() 中调用 services.AddMvc() (或 services.AddMvcCore())时,会自动注册此模型绑定器
| 归档时间: |
|
| 查看次数: |
6255 次 |
| 最近记录: |