在Visual Studio中调试时底层连接已关闭错误
我们正在使用访问Web API REST Web服务的Web API客户端。在Visual Studio中调试时底层连接已关闭错误
An error occured while sending the request (Inner Exception: The underlying conection was closed: An unexpected error occured on a send)
这仅在Visual Studio 2015年没有debbugging运行代码时,它不会发生在调试时发生的情况:
我们呼吁这在调试时,收到以下错误。 我们使用.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);
}
这似乎是由Windows Update KB4041083引起的。 我们卸载了此更新,然后再次正常工作。
很高兴知道它已经解决,您可以将其标记为答案,这样可以帮助其他社区成员解决您的问题。感谢您的分享。 –
有几个原因导致这样的错误,所以你可以检查以下
你已经正确配置的设置。 系统中的防火墙允许您网络中配置的连接(协议,主机&端口) DNS服务器能够解析主机。 由于任何原因,您的ISP不会阻止您的连接 由于您的错误没有固定的解决方案,因此您可能需要努力解决实际问题。如果启用,您还可以从日志文件中找到一些有用的信息。
如果用户正在调试它,那么它很可能运行在IISExpress而不是IIS中(尽管这是可能的)。如果是这种情况,那么它不太可能是外部DNS或网络问题,而是本地机器本身。 – DiskJunky
当我们在没有调试的情况下在同一台PC上运行应用程序时,它按预期工作。这只发生在Visual Studio中的debbugging时。因此我认为网络设置可以。 – Alexander
Web API服务在我们网络内的服务器上运行。我们只调试客户端应用程序。 Web服务是我们的生产Web服务。当通过其他PC调用时以及在不调试应用程序的情况下运行应用程序时,Web Service运行正常。 – Alexander
在调试同一个项目时,这是否发生在另一台机器上? – DiskJunky
发生这种情况时,您是否在代码中放置了任何断点?或者你只是用调试器运行,但不能在任何地方破坏?它总是发生还是偶尔发生? – Evk
我有第二台PC与Windows 10和Visual Studio 2017.一切正常运行。我可以正常调试应用程序。 发生此问题的PC在Visual Studio 2015的Windows 7上运行。 – Alexander