0

I am trying to connect to an API using RestSharp however I am getting the following error:

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond <ipaddress>:<port>

Code:

var client = new RestClient("https://api.infobip.com/sms/1/text/advanced");

var request = new RestRequest(Method.POST);
request.AddHeader("accept", "application/json");
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "Basic " + Base64Encode());
request.AddParameter("application/json", ReturnJsonData(sms), ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

The weird thing is that code works perfect in a console application but it fails to connect in a web application. Help please.

msmolcic
  • 6,407
  • 8
  • 32
  • 56
Walters
  • 119
  • 16
  • 2
    If the code works in a console app, but the same exact code does not work in a web app, then the problem is likely not with this code but with the supporting code/architecture in the web app. Where does this code live in your web app? Does it run in a controller? In startup? – maccettura Oct 14 '19 at 17:18
  • Thanks for the info nut It is not in a global or controller. This is a asp.net web forms project and it is in a regular button click. – Walters Oct 14 '19 at 17:23

1 Answers1

0

The problem you are facing may not be because of code, rather it is due to the TLS.

If you are in dotnet framework 4.5 and above use below code in Startup.cs

public void Configuration(IAppBuilder app) {
        System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
        ConfigureAuth(app);
    }

If you are using .net framework below 4.5 then use below code in Global.asax

 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //TLS 1.2
 ServicePointManager.SecurityProtocol = (SecurityProtocolType)768; //TLS 1.1