我遇到了一个与.NET HttpClient类相关的问题(.NET 4.5.1,System.Net.Http v4.0.0.0)。我调用HttpClient.GetAsync方法,并传入CancellationToken(作为抽象化WebService之间调用的Nuget包的一部分)。如果在调用之前取消了令牌,则请求将通过而不会引发异常。这个行为似乎是不正确的。
我的测试(未完成,没有完全编写 - 没有异常检查):
我正在测试的方法是:
我知道在调用
为什么
我的测试(未完成,没有完全编写 - 没有异常检查):
[TestMethod]
public async Task Should_Cancel_If_Cancellation_Token_Called()
{
var endpoint = "nonexistent";
var cancellationTokenSource = new CancellationTokenSource();
var _mockHttpMessageHandler = new MockHttpMessageHandler();
_mockHttpMessageHandler
.When("*")
.Respond(HttpStatusCode.OK);
var _apiClient = new ApiClientService(new HttpClient(_mockHttpMessageHandler));
cancellationTokenSource.Cancel();
var result = await _apiClient.Get<string>(endpoint, null, cancellationTokenSource.Token);
}
我正在测试的方法是:
public async Task<T> Get<T>(string endpoint, IEnumerable<KeyValuePair<string, string>> parameters = null, CancellationToken cancellationToken = default(CancellationToken))
{
var builder = new UriBuilder(Properties.Settings.Default.MyEndpointHost + endpoint);
builder.Query = buildQueryStringFromParameters(parameters);
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
// After this, we really shouldn't continue.
var request = await _httpClient.GetAsync(builder.Uri, cancellationToken);
if (!request.IsSuccessStatusCode)
{
if (request.StatusCode >= HttpStatusCode.BadRequest && request.StatusCode < HttpStatusCode.InternalServerError)
{
throw new EndpointClientException("Service responded with an error message.", request.StatusCode, request.ReasonPhrase);
}
if (request.StatusCode >= HttpStatusCode.InternalServerError && (int)request.StatusCode < 600)
{
throw new EndpointServerException("An error occurred in the Service endpoint.", request.StatusCode, request.ReasonPhrase);
}
}
var json = await request.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(json);
}
catch (Exception ex)
{
throw;
}
}
我知道在调用
HttpClient.GetAsync
之前可以检查取消令牌的状态并在请求取消时抛出异常。我也知道可以注册委托以取消HttpClient请求。然而,似乎将令牌传递给HttpClient方法应该为我处理此事(否则,这有什么意义呢?),因此我想知道是否有什么我没有注意到的地方。我无法访问HttpClient
源代码。为什么
HttpClient.GetAsync
没有检查我的取消令牌并在传入时中止其进程?