Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters by POST to an Azure function?

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 contain the current date and a string parameters typed by the user and passed by GET.
  • 1 function similar to the previous one, but passing the parameter by POST.
  • 1 function to read the table and show its content.

I've been able to do the first and the third ones. But I can't pass the parameter by POST. I've looked for examples but I couldn't run them with success. The client app is a Windows Forms one.

Could anyone show me an example anout how to pass parameters by POST to the function and how to read them?

Thank's in advance

EDIT:

Here's the code to pass the parameters by GET (this is working fine):

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

And here's the code to receive it and do the insert (this is working too):

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

What I'm looking for is to to this by POST

like image 527
davidrgh Avatar asked Jul 19 '17 07:07

davidrgh


People also ask

How do you pass an optional parameter in Azure function?

You can express that a parameter is optional in the route template itself. For the route above, you can just change your template to the following: ResolveKey/{key}/{resolver?} For those who are looking to match a full path in the resolver, Azure function will url encode the {resolver?}

How do I pass the function key to Azure function?

Obtaining keys To view your keys, create new ones, or roll keys to new values, navigate to one of your HTTP-triggered functions in the Azure portal and select Function Keys. You can also manage host keys. Navigate to the function app in the Azure portal and select App keys.

What is HTTP trigger in Azure function?

About Http Triggered Function Apps These authorizations will works only after publishing the code in Azure. It can receive request data via query string parameters, request body data or URL route templates.


1 Answers

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);                      } 
like image 144
Allen Zhang Avatar answered Sep 21 '22 05:09

Allen Zhang