我们正在使用访问Web API REST Web服务的Web API客户端。
调试时调用它时出现以下错误:
An error occured while sending the request (Inner Exception: The underlying conection was closed: An unexpected error occured on a send)
仅在Visual Studio 2015中进行调试时才会发生这种情况。在没有调试的情况下运行代码时不会发生这种情况。 我们使用的是.NET 4.6.1。
为什么会这样?为什么在调试时没有调试和崩溃时运行它。您有什么想法我们如何解决这个问题以及我们可以检查什么?
我们使用以下代码进行Web服务调用:
public async Task<string> GetToken(string username, string password)
{
using (var client = new HttpClient())
{
InitializeHttpClient(client);
HttpContent requestContent = new StringContent("grant_type=password&username=" + username + "&password=" + password, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await client.PostAsync("token", requestContent);
if (response == null || response.StatusCode == HttpStatusCode.BadRequest)
return null;
if (response.StatusCode == HttpStatusCode.NotFound
|| response.StatusCode == HttpStatusCode.RequestTimeout
|| response.StatusCode == HttpStatusCode.BadGateway
|| response.StatusCode == HttpStatusCode.ServiceUnavailable)
{
throw new Exception("No Connection to Web Service");
}
var bearerData = response.Content.ReadAsStringAsync().Result;
return JObject.Parse(bearerData)["access_token"].ToString();
}
}
private void InitializeHttpClient(HttpClient client)
{
client.BaseAddress = new Uri(_webServiceAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("User-Agent", "Test Client");
}
private void InitializeHttpClient(HttpClient client, string token)
{
InitializeHttpClient(client);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);
}
答案 0 :(得分:2)
这似乎是由Windows Update KB4041083引起的。 我们卸载了此更新,然后一切正常。