2017-02-27 57 views
2

是否可以在Azure函數內部創建HTTP(s)發佈請求?我正在嘗試創建一個正在監聽一個服務的自定義webhook,並在觸發時通過HTTP使用post來調用另一個服務。Azure函數在函數內調用http發佈

我的代碼看起來像這樣:

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) 
{ 

    BitbucketRequest data = await req.Content.ReadAsAsync<BitbucketRequest>(); 
    //DO STH WITH DATA TO GET e.g. USER STORY ID 

    using(var client = new HttpClient()){ 
     client.BaseAddress = new Uri("https://SOME_TARGETPROCESS_URL/api/v1"); 
     var body = new { EntityState = new { Id = 174 } }; 
     var result = await client.PostAsJsonAsync(
         "/UserStories/7034/?resultFormat=json&access_token=MYACCESSTOKEN", 
         body); 
     string resultContent = await result.Content.ReadAsStringAsync(); 
    } 

    return req.CreateResponse<string>(HttpStatusCode.OK,"OKOK"); 
} 

我想這個問題是當前HttpRequestMessage佔據網絡插座,我無法創建新的HTTP請求。

的錯誤,我在例外的細節中發現:

  • 基礎連接已關閉:上一個發送發生意外的錯誤。
  • 無法從傳輸連接讀取數據:現有連接被遠程主機強制關閉。
  • 插座異常錯誤代碼:10054
+1

找到該問題默認情況下,不支持TLS 1.2(這是我調用的端點所使用的)。 System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; –

+0

你是對的;這也適用於我! –

回答

0

我已經做了Azure的功能裏面的HTTP後,像這樣:

using System.Net; 
using System.Net.Http; 
using System.Net.Http.Headers; 
using System.Text; 
using Newtonsoft.Json; 

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, string arg1, string arg2, string arg3, TraceWriter log) 
{ 
    log.Info("C# HTTP trigger function processed a request."); 
    var text = String.Format("arg1: {0}\narg2: {1}\narg3: {2}", arg1, arg2, arg3); 
    log.Info(text); 

    var results = await SendTelegramMessage(text); 
    log.Info(String.Format("{0}", results)); 

    return req.CreateResponse(HttpStatusCode.OK); 
} 

public static async Task<string> SendTelegramMessage(string text) 
{ 
    using (var client = new HttpClient()) 
    { 

     Dictionary<string, string> dictionary = new Dictionary<string, string>(); 
     dictionary.Add("PARAM1", "VALUE1"); 
     dictionary.Add("PARAM2", text); 

     string json = JsonConvert.SerializeObject(dictionary); 
     var requestData = new StringContent(json, Encoding.UTF8, "application/json"); 

     var response = await client.PostAsync(String.Format("url"), requestData); 
     var result = await response.Content.ReadAsStringAsync(); 

     return result; 
    } 
} 

正如你可以通過名字猜測,我使用這個送POST請求的電報BOT

3

這當然是可能的,下面的代碼塊在我的測試功能非常有效:

using(var client = new HttpClient()) 
{ 
    client.BaseAddress = new Uri("https://www.google.com"); 
    var result = await client.GetAsync(""); 
    string resultContent = await result.Content.ReadAsStringAsync(); 
    log.Info(resultContent); 
} 

它打印出google.com的HTML。 POST也有效:從谷歌返回錯誤405(方法不允許)!! 1。

難道你的被調用者失敗了嗎?

+2

值得指出的是,在函數中使用HttpClient時應該知道這種反模式。 https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/ – Aidos

0

我剛剛花了好幾個小時,試圖讓這個工作。這是在NodeJS中。 我想到的事情是,我顯然需要有一個端點運行HTTPS和有效的證書。

不確定這是否記錄在任何地方。