Alexander
Alexander

Reputation: 1061

The underlying connection was closed error when debugging in Visual Studio

We are using a Web API Client that accesses a Web API REST Web Service.

We are getting the following error when calling this when Debugging:

An error occured while sending the request (Inner Exception: The underlying conection was closed: An unexpected error occured on a send)

This only happens when Debugging in Visual Studio 2015. It does not happen when running the Code without debbugging. We are using .NET 4.6.1.

Why does this happen? Why does it run when not Debugging and Crash when Debugging. Do you have any ideas how we can solve this Problem and what we can check?

We use the following Code to make the web Service calls:

    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);

    }

Upvotes: 2

Views: 961

Answers (1)

Alexander
Alexander

Reputation: 1061

This seems to be caused by Windows Update KB4041083. We deinstalled this update and then everything worked normal again.

Upvotes: 2

Related Questions