是否可以在Azure功能中创建HTTP(s)发布请求?我正在尝试创建一个正在侦听一个服务的自定义webhook,当被触发时,它会使用post通过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占用了Web套接字,我无法创建新的Http请求。
我在例外详情中发现的错误:
答案 0 :(得分:4)
当然可以使用以下代码块在我的测试函数中正常工作:
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。
可能是你的被叫失败了吗?
答案 1 :(得分:3)
我在Azure Function中完成了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请求
答案 2 :(得分:2)
对于在Azure函数中搜索HttpClient时落入此处的其他人。
https://docs.microsoft.com/en-us/azure/azure-functions/manage-connections
// Create a single, static HttpClient
private static HttpClient httpClient = new HttpClient();
public static async Task Run(string input)
{
var response = await httpClient.GetAsync("https://example.com");
// Rest of function
}
答案 3 :(得分:1)
我花了几个小时自己试图让它发挥作用。这是在NodeJS中。 我想到的是,我显然需要有一个端点运行HTTPS,并且有一个有效的证书。
不确定是否记录在任何地方。
答案 4 :(得分:0)
那时,Azure Functions中未启用对TLS 1.2的支持。另一方面,端点使用的是TLS 1.2。
在发送POST请求之前添加此代码即可解决问题:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;