How to pass parameters by POST to an Azure function? How to pass parameters by POST to an Azure function? azure azure

How to pass parameters by POST to an Azure function?


In case google took you here, this is how it's done in March 2019 (Azure Functions v3):

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);                    }


To get the request content from the request body(post request), you could use req.Content.ReadAsAsync method. Here is the code sample.

Sample request body.

{    "name": "Azure"}

Define a class to deserialize the post data.

public class PostData{    public string name { get;set; }    }

Get the post data and display it.

PostData data = await req.Content.ReadAsAsync<PostData>();log.Info("name:" + data.name);

Client side code to send the post request.

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("function-url");req.Method = "POST";req.ContentType = "application/json";Stream stream = req.GetRequestStream();string json = "{\"name\": \"Azure\" }";byte[] buffer = Encoding.UTF8.GetBytes(json);stream.Write(buffer,0, buffer.Length);HttpWebResponse res = (HttpWebResponse)req.GetResponse();


If you are using System.Text.Json, you can read the POST data in one line:

public static async Task Run(    [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]    HttpRequest req,    ILogger log){    MyClass myClass = await JsonSerializer.DeserializeAsync<MyClass>(req.Body);}

If you are using Newtonsoft.Json, see the answer by Allen Zhang.