How to pass parameters by POST to an Azure function?
Solution 1:
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);
}
Solution 2:
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();
Solution 3:
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.
Solution 4:
For passing parameters as POST request, you need to do following things:
-
Make Json model of the parameters that u need to pass,ex:
{"UserProfile":{ "UserId":"xyz1","FirstName":"Tom","LastName":"Hank" }}
-
Post your data model using client like POSTMAN
-
Now you will get the posted content in HttpRequestMessage body, sample code is as follows:
[FunctionName("TestPost")] public static HttpResponseMessage POST([HttpTrigger(AuthorizationLevel.Function, "put", "post", Route = null)]HttpRequestMessage req, TraceWriter log) { try { //create redis connection and database var RedisConnection = RedisConnectionFactory.GetConnection(); var serializer = new NewtonsoftSerializer(); var cacheClient = new StackExchangeRedisCacheClient(RedisConnection, serializer); //read json object from request body var content = req.Content; string JsonContent = content.ReadAsStringAsync().Result; var expirytime = DateTime.Now.AddHours(Convert.ToInt16(ConfigurationSettings.AppSettings["ExpiresAt"])); SessionModel ObjModel = JsonConvert.DeserializeObject<SessionModel>(JsonContent); bool added = cacheClient.Add("RedisKey", ObjModel, expirytime); //store to cache return req.CreateResponse(HttpStatusCode.OK, "RedisKey"); } catch (Exception ex) { return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "an error has occured"); } }