Web API:使用CancellationToken的DelegatingHandler

Ton*_*ony 1 asp.net-web-api cancellation-token

典型的Web API DelegatingHandler实现看起来像这样......

protected async override Task<HttpResponseMessage> SendAsync(
    HttpRequestMessage request, CancellationToken cancellationToken)
{
    // TODO: Do work before inner handler here

    // Call the inner handler.
    var response = await base.SendAsync(request, cancellationToken);

    // TODO: Do work _after_ inner handler here

    return response;
}
Run Code Online (Sandbox Code Playgroud)

处理CancellationToken.IsCancellationRequested == true的首选方法是什么?

我是不是该:

  • 生成错误响应并打破委托链?
  • 什么都不做(如上所述)?
  • 选项'C'?

Ste*_*ary 5

取消语义是在取消令牌时抛出异常(例如CancellationToken.ThrowIfCancellationRequested).

如果您没有任何异步工作要做(除了base.SendAsync),那么您可以忽略该令牌.

请注意,await base.SendAsync如果令牌被取消,可能会引发异常.异常将自然传播,但如果您有任何必须进行的清理,无论取消,请使用usingfinally阻止.