带有 http 触发器的 Python Azure 函数看不到 json 正文

问题描述

我正在本地构建一个 Blazor 服务器应用程序,它调用一个用 Python 编写的 azure 函数。我正在我的本地机器上使用 Visual Studio 为 Blazor 应用程序和 Python 函数的 VS 代码进行开发。 Python 是 3.8.7

Blazor 应用程序使用 PostAsJsonAsync 作为正文中的 json 数据将数据发送到 http://localhost:7071/api/xxxxx 的 azure 函数。我已经测试过使用 webhook.site 可以正常工作。 JSON 数据(主要)是一个 base64 编码的 .wav 文件

对 PostAsJsonAsync 的调用似乎被 python azure 函数看到,并且“有点”工作,好像我向调用添加一个参数我可以读取它。然而,python 函数总是将正文报告为零长度。

我做错了什么?

解决方法

  • 检查您是否正在发送如下请求:

     var modelNew = new Model() { Description = "willekeurige klant",Name = "John Doe" };                     response = await client.PostAsJsonAsync("api/ModelsApi/",modelNew); 
    
     if (response.IsSuccessStatusCode) //check is response succeeded
     {
                       // Do something
     }
    
  • 而且,阅读如下:

    import logging
    import azure.functions as func
    
    
    def main(req: func.HttpRequest) -> func.HttpResponse:
      logging.info('Python HTTP trigger function processed a request.')
    
      name = req.params.get('name')
      if not name:
          try:
              req_body = req.get_json()
          except ValueError:
              pass
          else:
              name = req_body.get('name')
    
      if name:
          return func.HttpResponse(f"Hello {name}!")
      else:
          return func.HttpResponse(
              "Please pass a name on the query string or in the request body",status_code=400
          )
    
  • 检查您是否使用此代码对其进行编码:

      private static string Base64Encode(string plainText)
      {
          var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
          return System.Convert.ToBase64String(plainTextBytes);
      }
    

此外,请考虑在 Azure Blob 存储中使用 .wav 之类的文件,并传递它的 url 位置而不是整个对象以提高安全性。