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
1
  • Don't use WebRequest, it's old and broken. Use HttpClient instead. Commented Oct 24, 2020 at 22:51

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.