【问题标题】:How to call external api with Azure function with POST method with request body data如何使用带有请求正文数据的 POST 方法使用 Azure 函数调用外部 api
【发布时间】:2021-11-07 19:13:28
【问题描述】:
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;

namespace FunctionRestApi
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
    {

            var httpWebRequest = (HttpWebRequest)WebRequest.Create("URL_with_client_id_authorization_token");
            httpWebRequest.ContentType = "application/json";

            httpWebRequest.Method = "GET";

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
               var result = streamReader.ReadToEnd();
               log.LogInformation(result);
            }

            return new OkObjectResult(value: httpWebRequest);
      }
   }
 }

我是天蓝色功能的新手。当我只使用“GET”方法时,此代码有效。但是,如果我想对请求正文数据(即日期范围(start_date 和 end_date)和其他一些 sub_user_id)使用“POST”方法,那么我该怎么做呢?

【问题讨论】:

    标签: c# azure-functions http-post


    【解决方案1】:

    下面是一个简单的使用HttpClient 和一些 cmets 的 POST 请求示例:

    using System;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Extensions.Http;
    using Microsoft.Extensions.Logging;
    using Newtonsoft.Json;
    
    namespace AzureFunctionsSandbox.Functions
    {
        public static class Function1
        {
            private static readonly HttpClient _httpClient = new HttpClient();
    
            [FunctionName("Function1")]
            public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest request,
                ILogger log)
            {
                // create request as an object to easily set values
                var myRequest = new MyRequest
                {
                    StartDate = DateTime.Now,
                    EndDate = DateTime.Now.AddDays(1),
                    SubUserId = "ABC123"
                };
    
                // serialize to JSON string for POST request body
                var myRequestJsonBody = JsonConvert.SerializeObject(myRequest);
    
                // .PostAsync() requires a HttpContent object - StringContent is a sub class
                var requestContent = new StringContent(myRequestJsonBody, Encoding.UTF8, "application/json");
    
                // make the POST request
                var response = await _httpClient.PostAsync("URL_with_client_id_authorization_token", requestContent);
    
                // use response body for further work if needed...
                var responseBody = response.Content.ReadAsStringAsync();
    
                return new OkResult();
            }
        }
    
        public class MyRequest
        {
            [JsonProperty(PropertyName = "start_date")]
            public DateTime StartDate { get; set; }
    
            [JsonProperty(PropertyName = "end_date")]
            public DateTime EndDate { get; set; }
    
            [JsonProperty(PropertyName = "sub_user_id")]
            public string SubUserId { get; set; }
        }
    }
    

    https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-5.0

    【讨论】:

      【解决方案2】:

      请参阅此 SO question 中的答案之一,它显示了如何使用 HttpClient 类进行 POST 调用,但是它正在创建它的新实例,这不是正确的方法。最佳做法是在您的函数应用中仅使用 HttpClient 的静态对象。

      【讨论】:

        【解决方案3】:

        首先检查 POSTMAN 如何使用 BASIC/BEARER 身份验证配置连接到外部 API,然后您可以使用相同的配置编写代码

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-05-24
          • 1970-01-01
          • 2014-12-06
          • 2018-06-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多