简体   繁体   中英

How to invoke an Azure HTTP trigger function

I have an Azure HTTP trigger function that can be invoked satisfactorily as a URL in a browser, or through Postman. How do call it from C#?

The function is

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

My code to use it is

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

The call to request.GetResponse() fails and Visual Studio reports:

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

As per this and this SO answers, it might be the case where security protocols might not be matching between the client and the server hence it is throwing the error that you see. You can try setting the securityProtocol to Tsl version which your client framework can support before calling request.GetResponse() .

Something like this-

WebRequest request = WebRequest.Create(url);

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

WebResponse response = request.GetResponse();

Also, as per this MS remark, you should move towards using HttpClient instead of WebRequest

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM