如何使用Azure Function以POST方式调用外部API并传递请求体参数
Azure Function POST调用外部API实现方案
基于原有HttpWebRequest的修改版本
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System.Net; using System.IO; using System.Text.Json; namespace FunctionRestApi { // 定义外部API请求参数封装类 public class ExternalApiRequest { public string sub_user_id { get; set; } public string start_date { get; set; } public string end_date { get; set; } } public static class Function1 { [FunctionName("Function1")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { // 可选:如果参数需要从调用当前Function的请求中获取,打开下方注释读取 // string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); // var inputParam = JsonSerializer.Deserialize<ExternalApiRequest>(requestBody); // 构造调用外部API的请求参数 var apiParam = new ExternalApiRequest { sub_user_id = "实际的用户ID", start_date = "2024-01-01", end_date = "2024-01-31" // 如果用上面读取的传入参数,这里就赋值为inputParam对应的属性即可 }; var httpWebRequest = (HttpWebRequest)WebRequest.Create("URL_with_client_id_authorization_token"); httpWebRequest.ContentType = "application/json"; // 请求方法改为POST httpWebRequest.Method = "POST"; // 序列化参数并写入POST请求体 var jsonParam = JsonSerializer.Serialize(apiParam); using (var requestStream = httpWebRequest.GetRequestStream()) using (var streamWriter = new StreamWriter(requestStream)) { await streamWriter.WriteAsync(jsonParam); await streamWriter.FlushAsync(); } string result = string.Empty; var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { result = await streamReader.ReadToEndAsync(); log.LogInformation(result); } // 修复返回值,返回外部API的实际响应内容 return new OkObjectResult(result); } } }
核心修改说明
- 新增
ExternalApiRequest类封装需要传递的三个业务参数,方便JSON序列化操作,参数类型可根据实际业务要求调整为DateTime、int等对应类型 - 将外部API请求方法从
GET调整为POST - 新增请求体写入逻辑,把序列化后的JSON参数写入POST请求的请求流中
- 调整方法为异步实现,避免同步IO阻塞导致的性能问题,更适配Azure Function的运行环境
- 修复原有返回值错误,改为返回外部API的实际响应内容
- 提供了从当前Function触发请求中读取参数的可选实现,如果你需要调用方把参数传给Function再透传给外部API,直接打开对应注释即可使用
更推荐的实现方式(HttpClient版本)
HttpWebRequest已经被官方标记为过时,更推荐使用HttpClient配合IHttpClientFactory使用,避免端口耗尽问题,核心调用逻辑示例如下:
// 注入HttpClient,Program.cs中添加builder.Services.AddHttpClient(); public static class Function1 { [FunctionName("Function1")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log, IHttpClientFactory httpClientFactory) { var client = httpClientFactory.CreateClient(); client.DefaultRequestHeaders.Add("Authorization", "你的认证Token"); var apiParam = new ExternalApiRequest { sub_user_id = "实际的用户ID", start_date = "2024-01-01", end_date = "2024-01-31" }; var response = await client.PostAsJsonAsync("外部API地址", apiParam); response.EnsureSuccessStatusCode(); var result = await response.Content.ReadAsStringAsync(); log.LogInformation(result); return new OkObjectResult(result); } }
内容的提问来源于stack exchange,提问作者new_bie_new
相关产品推荐
相关产品推荐

