0

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
Frank H
  • 13
  • 4

1 Answers1

2

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

akg179
  • 1,287
  • 1
  • 6
  • 14
  • 1
    It needed the change to both HttpClient and the security protocol. Also after changing from .Net Framework 4.5.2 (default in my VS, probably left from an old project) to latest version shown, 4.7.2, the security protocol doesn't need to be set explicitly, as recommended [here](https://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls) – Frank H Oct 24 '20 at 23:35