2017-07-19 21 views
6

Tôi đang cố gắng thực hiện một chức năng Azure đơn giản để tìm hiểu về nó. Sẽ có 3 chức năng:Làm cách nào để chuyển các tham số bằng POST sang một hàm Azure?

  • 1 chức năng để chèn hàng vào bảng cơ sở dữ liệu. Bảng này sẽ chứa ngày hiện tại và một tham số chuỗi được người dùng nhập và được truyền bởi GET.
  • 1 chức năng tương tự như hàm trước, nhưng chuyển tham số bằng POST.
  • 1 chức năng để đọc bảng và hiển thị nội dung của bảng.

Tôi đã có thể thực hiện việc đầu tiên và thứ ba. Nhưng tôi không thể chuyển tham số bằng POST. Tôi đã tìm kiếm các ví dụ nhưng tôi không thể chạy chúng với thành công. Ứng dụng khách là một Windows Forms.

Có ai có thể cho tôi xem ví dụ về cách chuyển các tham số bằng POST tới hàm và cách đọc chúng không?

Thank của trước

EDIT:

Dưới đây là đoạn code để vượt qua các thông số của GET (điều này đang làm việc tốt):

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

    } 
} 

Và đây là đoạn code để đón nhận nó và làm chèn (điều này cũng đang hoạt động):

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

Điều tôi đang tìm là để t của mình bằng cách POST

+0

Hãy gửi ví dụ chức năng của bạn cho đến nay. Bạn viết chúng bằng ngôn ngữ nào? Bạn có thể viết các hàm Azure trong JavaScript dựa vào Node.js, nhưng cũng C# cho ASP.NET: https://visualstudiomagazine.com/articles/2017/04/01/implementing-webhooks-azure-functions.aspx – Dai

+0

Xin lỗi; Tôi đang sử dụng C# để mã các ứng dụng. Tôi đã thêm mã tôi đã thực hiện. – davidrgh

Trả lời

7

Để nhận nội dung yêu cầu từ nội dung yêu cầu (yêu cầu bài đăng), bạn có thể sử dụng phương thức req.Content.ReadAsAsync. Đây là mẫu mã.

Cơ thể yêu cầu mẫu.

{ 
    "name": "Azure" 
} 

Xác định lớp để loại bỏ dữ liệu bài đăng.

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

Tải dữ liệu bài đăng và hiển thị nó.

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

Mã phía máy khách để gửi yêu cầu đăng bài.

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

Bạn cần phải đính kèm dữ liệu vào phần thân của bài yêu cầu và xử lý nó đúng cách:

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

Bạn có thể tìm thấy một ví dụ hơi khác nhau here và ví dụ chính xác here.

1

Chuỗi truy vấn (cặp tên/giá trị) theo mặc định được gửi trong phần nội dung thư HTTP của yêu cầu POST chứ không phải dưới dạng chuỗi truy vấn. Phương thức GetQueryNameValuePairs sẽ phân tích chuỗi truy vấn và theo mặc định sẽ không hoạt động với yêu cầu POST.

Đối với POST yêu cầu bạn có thể sử dụng một cái gì đó tương tự như sau:

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

Xin lưu ý rằng mã này KHÔNG được sản xuất sẵn sàng (Async Deadlocks) –

1

Đối với truyền thông số như yêu cầu POST, bạn cần phải làm những việc sau đây:

  1. Hãy Json mô hình của các thông số mà bạn cần phải vượt qua, ví dụ:

    {"UserProfile":{ "UserId":"xyz1","FirstName":"Tom","LastName":"Hank" }} 
    
  2. Đăng mô hình dữ liệu của bạn bằng khách hàng như Postman

    enter image description here

  3. Bây giờ bạn sẽ nhận được nội dung đăng tải trong HttpRequestMessage cơ thể, mẫu mã như sau:

    [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"); 
        } 
    } 
    
Các vấn đề liên quan