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

我正在尝试使用简单的Azurefunction来了解它。 将有3个function:

  • 1用于将行插入数据库表的函数。 该表将包含当前日期和用户键入并由GET传递的字符串参数。
  • 1function类似于前一个,但通过POST传递参数。
  • 1函数读取表并显示其内容。

我已经能够完成第一个和第三个。 但我不能通过POST传递参数。 我找了一些例子,但我不能成功地运行它们。 客户端应用程序是Windows窗体。

谁能告诉我一个例子,如何通过POST将参数传递给函数以及如何阅读它们?

提前致谢

编辑:

这是通过GET传递参数的代码(这很好):

private void button2_Click(object sender, EventArgs e) { string cadena = lsql1.Text + "?notas=" + tNotas.Text; try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(cadena); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); if (res.StatusCode == HttpStatusCode.OK) { MessageBox.Show("Grabado"); } else { MessageBox.Show(res.StatusDescription); } }catch (WebException ex) { using (Stream s = ex.Response.GetResponseStream()) { StreamReader sr = new StreamReader(s); string text = sr.ReadToEnd(); text = text.Substring(1, text.Length - 2); sr.Close(); text = text.Replace("\\", ""); text = "{" + text + "}"; Error mensajeError = JsonConvert.DeserializeObject(text); MessageBox.Show(mensajeError.ExceptionMessage); } } } 

这是接收它并执行插入的代码(这也是有效的):

 [FunctionName("sql1")] public static async Task Run(HttpRequestMessage req, TraceWriter log) { try { log.Info("C# HTTP trigger function processed a request."); var cnnString = "Server=SERVIDOR;Database=base_prueba;User ID =azure;Password=0000;Trusted_Connection=False;Encrypt=False;"; using (SqlConnection connection = new SqlConnection(cnnString)) { connection.Open(); SqlCommand cmd = connection.CreateCommand(); DateTime fecha = DateTime.Today; string notas = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "notas", true) == 0) .Value; // insert a log to the database cmd.CommandText = "INSERT INTO Prueba_Azure (fecha, notas) VALUES ('" + fecha.ToString() + "', '" + notas + "')"; cmd.ExecuteNonQuery(); } // Get request body dynamic data = await req.Content.ReadAsAsync(); return name == req.CreateResponse(HttpStatusCode.OK, "Done"); } catch (Exception ex) { HttpResponseMessage res = req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex); return res; } } 

我正在寻找的是POST

要从请求正文中获取请求内容(发布请求),您可以使用req.Content.ReadAsAsync方法。 这是代码示例。

样品申请机构。

 { "name": "Azure" } 

定义一个类来反序列化后期数据。

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

获取发布数据并显示它。

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

客户端代码发送post请求。

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

要将参数作为POST请求传递,您需要执行以下操作:

  1. 制作你需要通过的参数的Json模型,例如:

     {"UserProfile":{ "UserId":"xyz1","FirstName":"Tom","LastName":"Hank" }} 
  2. 使用POSTMAN等客户端发布数据模型

    在此处输入图像描述

  3. 现在您将在HttpRequestMessage体中获取发布的内容,示例代码如下:

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

您需要将数据附加到post请求的正文并正确处理它:

 public static async Task Run(HttpRequestMessage req, TraceWriter log) { // This reads your post request body into variable "data" string data = await req.Content.ReadAsStringAsync(); // Here you can process json into an object dynamic parsed = JsonConvert.DeserializeObject(data); return exitstring == null ? req.CreateResponse(HttpStatusCode.BadRequest, "Something went wrong, sorry") : req.CreateResponse(HttpStatusCode.OK); } 

你可以在这里找到一个稍微不同的例子和这里的确切例子。

默认情况下,查询字符串(名称/值对)在POST请求的HTTP消息正文中发送,而不是作为查询字符串发送。 GetQueryNameValuePairs方法将解析查询字符串,默认情况下不会使用POST请求。

对于POST请求,您可以使用类似于此的内容:

 var content = request.Content; string contentInString = content.ReadAsStringAsync().Result;