2017-07-19 150 views
6

我正在尝试做一个简单的Azure函数来了解它。将会有3个函数:如何通过POST将参数传递给Azure函数?

  • 1函数向数据库的表中插入一行。该表将包含当前日期和由用户键入并通过GET传递的字符串参数。
  • 1函数类似于上一个,但是通过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<Error>(text); 

      MessageBox.Show(mensajeError.ExceptionMessage); 
     } 

    } 
} 

而这里的代码来接受它,做插入(这也是工作):

[FunctionName("sql1")] 
public static async Task<HttpResponseMessage> 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<object>(); 

     return name == req.CreateResponse(HttpStatusCode.OK, "Done"); 
    } 
    catch (Exception ex) 
    { 
     HttpResponseMessage res = req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex); 
     return res; 
    } 
} 

我在找的是t他通过POST

+0

请发表您的函数的例子至今。你在写什么语言?您可以在JavaScript中针对Node.js编写Azure函数,也可以在ASP.NET中编写C#:https://visualstudiomagazine.com/articles/2017/04/01/implementing-webhooks-azure-functions.aspx – Dai

+0

对不起,我正在使用C#编写应用程序。 我已经添加了我所做的代码。 – davidrgh

回答

7

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

示例请求正文。

{ 
    "name": "Azure" 
} 

定义一个类来反序列化发布数据。

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

获取发布数据并显示它。

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

发送发布请求的客户端代码。

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

您需要将数据附加到POST请求的身体和正确处理它:

public static async Task<HttpResponseMessage> 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); 
} 

你可以找到一个稍微不同的例子here和准确的例子here

1

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

对于POST请求,你可以使用类似这样:

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

请注意,此代码不是生产就绪(异步死锁) –

1

传递参数作为POST请求,你需要做以下的事情:

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

    {"UserProfile":{ "UserId":"xyz1","FirstName":"Tom","LastName":"Hank" }} 
    
  2. 使用你的数据模型像邮差

    enter image description here

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