仕事やプライベートで調べたことのメモ書きなど(@札幌)

仕事やプライベートで調べたこと、興味ある事のメモ書きです。2016年4月から札幌で働いてます。※このブログは個人によるもので、団体を代表するものではありません。

C#でのAzure Functionsの呼び出しにはまった

Azure Functions(HttpTrigger)で何らかのFunctionsを追加すると、通常は、
https://xxxxxx.azurewebsites.net/api/xxxxx的なURLが作成されます。

で、以下のコードを書きました。

        WebClient wc = new WebClient();
        string url = "https://xxxxxx.azurewebsites.net/api/xxxxx";
        Stream st = wc.OpenRead(url);
        Encoding enc = Encoding.GetEncoding("utf-8");
        StreamReader sr = new StreamReader(st, enc);
        string html = sr.ReadToEnd();
        sr.Close();
        st.Close();
        Console.WriteLine(html);

そうると、、、、呼び出し時にエラーとなります。

>bin\Debug\ConsoleApplication1.exe

ハンドルされていない例外: System.Net.WebException: 接続が切断されました: 送信時に、予期しないエラーが発生しました。。 ---> System.IO.IOException: 転送接続からデータを読み取れません: 既存の接続はリモート ホストに強制的に切断されました。。 ---> System.Net.Sockets.SocketException: 既存の接続はリモート ホストに強制的に切断されました。
   場所 System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
:
:

Functionsの何か書き方がまずいのかとか、、、半日くらいいろいろ試行錯誤しました。
一晩寝たところ、なんと https を http に変えたら動くんじゃないかという神のお告げが。。。。
そして見事動きました!

でも何か悶々としていて、数日後にググってみると、今のページへめぐり逢い。。。。

fullvirtue.com
ちなみにHttpClientでも同様なようです。
qiita.com

なんと、一行追加するだけで動きましたとさ。

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        WebClient wc = new WebClient();
        string url = "https://xxxxxx.azurewebsites.net/api/xxxxx";
        Stream st = wc.OpenRead(url);
        Encoding enc = Encoding.GetEncoding("utf-8");
        StreamReader sr = new StreamReader(st, enc);
        string html = sr.ReadToEnd();
        sr.Close();
        st.Close();
        Console.WriteLine(html);

めでたしめでたし。