如何通过 POST 将参数传递给 Azure Functions 2

Pra*_*mar 2 c# post azure azure-functions

我想将参数传递给 Azure 函数 2 中的 HttpTrigger 类型。我在下面的链接中看到了 Azure 函数 1 的答案。

如何通过 POST 将参数传递给 Azure 函数?

上面链接中await req.Content.ReadAsAsync<>(); 的答案是我正在寻找 Azure Function 2 的类似答案。

这里我们使用 HttpRequest 类而不是 HttpRequestMessage 类。

下面是代码。

public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            string data = .............;
        }
Run Code Online (Sandbox Code Playgroud)

Md *_*ron 7

看来您正在尝试将POST请求发送到Azure Function V2. 请参阅下面的代码片段。

自定义请求类:

public class Users
    {

        public string Name { get; set; }
        public string Email { get; set; }

    }
Run Code Online (Sandbox Code Playgroud)

Azure 函数 V2:

在此示例中,我使用自定义类获取两个参数,并将该两个类属性作为响应返回。

public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            //Read Request Body
            var content = await new StreamReader(req.Body).ReadToEndAsync();

            //Extract Request Body and Parse To Class
            Users objUsers = JsonConvert.DeserializeObject<Users>(content);

            //As we have to return IAction Type So converting to IAction Class Using OkObjectResult We Even Can Use OkResult
            var result = new OkObjectResult(objUsers);
            return (IActionResult)result;
        }
Run Code Online (Sandbox Code Playgroud)

索取样品:

{
   "Name": "Kiron" ,
   "Email": "kiron@email.com"
}
Run Code Online (Sandbox Code Playgroud)

邮递员测试:

在此处输入图片说明

注意: 您正在寻找从您的函数await req.Content.ReadAsAsync<>();发送POST请求实际需要的。并从该服务器响应中读取。但请记住,req.Content不支持阅读帖子请求,Azure Function V2其中已显示Function V1示例here

另一个例子:

请参阅以下代码片段:

{
   "Name": "Kiron" ,
   "Email": "kiron@email.com"
}
Run Code Online (Sandbox Code Playgroud)

希望您理解,如果您还有任何疑问,请随时分享。谢谢和快乐编码!


Ram*_*sad 5

public static async void Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
            HttpRequest req,
            ILogger log)
        {
            var content = await new StreamReader(req.Body).ReadToEndAsync();

            MyClass myClass = JsonConvert.DeserializeObject<MyClass>(content);

        }
Run Code Online (Sandbox Code Playgroud)

您可以拥有一个自定义类,该类可以从 post 请求以 JSON 的形式发送。