How to pass parameters by POST to an Azure function?

前端 未结 9 1989
暗喜
暗喜 2020-12-24 05:27

I\'m trying to do a simple Azure Function to learn about it. There will be 3 functions:

  • 1 function to insert a row into a table of a database. This table will
9条回答
  •  一向
    一向 (楼主)
    2020-12-24 06:13

    For passing parameters as POST request, you need to do following things:

    1. Make Json model of the parameters that u need to pass,ex:

      {"UserProfile":{ "UserId":"xyz1","FirstName":"Tom","LastName":"Hank" }}
      
    2. Post your data model using client like POSTMAN

    3. 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(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");
          }
      }
      

提交回复
热议问题