c# - 如何调用 Azure HTTP 触发器函数
问题描述
我有一个 Azure HTTP 触发器函数,它可以作为浏览器中的 URL 或通过 Postman 令人满意地调用。如何从 C# 调用它?
功能是
public static class FunctionDemo
{
[FunctionName("SayHello")]
public static async Task<IActionResult> SayHello(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function 'SayHello' processed a request.");
return new OkObjectResult("Hello world");
}
}
我使用它的代码是
private void button1_Click(object sender, EventArgs e)
{
String url = "https://<app-name>.azurewebsites.net/api/SayHello";
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string reply = reader.ReadToEnd();
label1.Text = reply;
dataStream.Close();
}
对request.GetResponse()的调用失败,Visual Studio 报告:
System.Net.WebException - The underlying connection was closed: An unexpected error occurred on a send.
Inner Exception 1:
IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Inner Exception 2:
SocketException: An existing connection was forcibly closed by the remote host
解决方案
根据this和this SO的答案,可能是客户端和服务器之间的安全协议可能不匹配,因此它会抛出您看到的错误。您可以尝试在调用之前将 securityProtocol 设置为您的客户端框架可以支持的 Tsl 版本request.GetResponse()
。
像这样的东西-
WebRequest request = WebRequest.Create(url);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls |
SecurityProtocolType.Tls11 |
SecurityProtocolType.Tls12;
WebResponse response = request.GetResponse();
此外,根据此MS 评论,您应该转向使用HttpClient
而不是WebRequest
推荐阅读
- ios - SKStoreReviewController 未在开发中显示应用程序图标
- javascript - findByIdAndUpdate 一直被 .catch 捕获
- deep-learning - 为什么我们在 PyTorch 中“打包”序列?
- angular - 在 ng-cli 6 中公开等效功能
- python - 在循环中抓取多个页面会在第三级产生重复的结果
- ajax - 使用链接而不是按钮上传文件但接收 $_FILES 数组为空
- java - Jpcap 在尝试打开设备时崩溃
- scala - 如何使用 gatling JsonPath.query 从 JSON 字符串中检索值?
- java - Arrayadapter 和 SearchView
- swift - swift Eureka在多个条件下隐藏行