How to pass parameters by POST to an Azure functio

2019-03-18 15:40发布

问题:

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

回答1:

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


回答2:

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


回答3:

You need to attach data to the body of the post request and process it properly:

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

You can find a slightly different example here and the exact example here.



回答4:

The query string (name/value pairs) is by default sent in the HTTP message body of a POST request and not as query string. The GetQueryNameValuePairs method will parse the query string and will by default not work with POST request.

For the POST request you could use something similar to this:

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


回答5:

In case google took you here, this is how it's done in March 2019:

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

        }