【问题标题】:How to invoke an Azure HTTP trigger function如何调用 Azure HTTP 触发器函数
【发布时间】:2020-10-24 21:05:20
【问题描述】:

我有一个 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

【问题讨论】:

  • 不要使用WebRequest,它又旧又破。请改用HttpClient

标签: c# azure function


【解决方案1】:

根据thisthis SO 的回答,可能是客户端和服务器之间的安全协议可能不匹配,因此它会抛出您看到的错误。在调用request.GetResponse()之前,您可以尝试将securityProtocol设置为您的客户端框架可以支持的Tsl版本。

类似的东西-

WebRequest request = WebRequest.Create(url);

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | 
                                       SecurityProtocolType.Tls11 |
                                       SecurityProtocolType.Tls12;

WebResponse response = request.GetResponse();

另外,根据this MS 的评论,您应该改用HttpClient 而不是WebRequest

【讨论】:

  • 它需要同时更改 HttpClient 和安全协议。同样在从 .Net Framework 4.5.2(我的 VS 中的默认设置,可能来自旧项目)更改为显示的最新版本 4.7.2 之后,不需要显式设置安全协议,建议 here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
  • 2020-07-03
  • 2021-05-16
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多