【发布时间】:2017-10-09 14:58:35
【问题描述】:
我们正在使用访问 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。
为什么会这样?为什么不调试时运行,调试时崩溃。您对我们如何解决这个问题以及我们可以检查什么有什么想法吗?
我们使用以下代码进行网络服务调用:
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);
}
【问题讨论】:
-
调试同一个项目时,在不同的机器上是否会发生这种情况?
-
发生这种情况时,您是否在代码中放置了任何断点?或者你只是用调试器运行但没有在任何地方中断?它是总是发生还是偶尔发生?
-
我有第二台装有 Windows 10 和 Visual Studio 2017 的 PC。一切都在那里运行。我可以正常调试应用程序。出现此问题的 PC 正在 Windows 7 上运行 Visual Studio 2015。
-
我们已经尝试过带断点和不带断点。它总是在以下行崩溃: var response = await client.PostAsync("token", requestContent);
-
使用Fiddler等代理检查请求和响应。
标签: c# debugging visual-studio-2015 asp.net-web-api2