System.Net.WebException: 'The underlying connection was closed: An unexpected error occurred on a send.'

545 views Asked by At

I am trying to access a 3rd party API using "Basic" encoding but I am getting an exception with WebClient.DownloadData()

Here is the code

Controller

public string Get()
{
    return new MyModel().GetAll();
}

Model

public string GetAll()
{
    string auth = string.Format("{0}:{1}", username, password);
    string enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));
    client.Headers[System.Net.HttpRequestHeader.Authorization] = string.Format("{0} {1}","Basic", enc);
    string response = Encoding.Default.GetString(client.DownloadData(url)); // fails here (please see screenshot)
}

enter image description here

Similar questions on internet/stackoverflow say the solution is to check the SecurityProtocol

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
//I added 'SecurityProtocolType.Ssl3' but it didn't help. I am still getting the same error.

I added SecurityProtocol in Controller as well as in Global.asax.cs but no luck.

I am using Windows 11 for calling the API

.NET Framework of project is 4.6.1

Can anyone help me with this, please?

0

There are 0 answers