【问题标题】:How to connect to API using Restsharp如何使用 Restsharp 连接到 API
【发布时间】:2019-10-14 17:12:27
【问题描述】:

我正在尝试使用 RestSharp 连接到 API,但出现以下错误:

连接尝试失败,因为连接方在一段时间后没有正确响应, 或建立连接失败,因为连接的主机没有响应<ipaddress>:<port>

代码:

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

奇怪的是,代码在控制台应用程序中运行良好,但无法在 Web 应用程序中连接。请帮忙。

【问题讨论】:

  • 如果代码在控制台应用程序中有效,但相同的代码在 Web 应用程序中无效,则问题可能不在于此代码,而在于 Web 应用程序中的支持代码/架构.此代码在您的 Web 应用程序中的什么位置?它在控制器中运行吗?在启动中?
  • 感谢您的信息坚果它不在全局或控制器中。这是一个 asp.net 网络表单项目,它是在常规按钮单击中。

标签: c# asp.net restsharp infobip infobip-api


【解决方案1】:

您面临的问题可能不是因为代码,而是由于 TLS。

如果您使用的是 dotnet framework 4.5 及更高版本,请在 Startup.cs 中使用以下代码

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

如果您使用 4.5 以下的 .net 框架,请在 Global.asax 中使用以下代码

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    • 2020-06-24
    • 2020-06-19
    • 2013-10-12
    • 2013-05-18
    • 1970-01-01
    相关资源
    最近更新 更多