2013-03-04 36 views
5

Tôi muốn thực hiện chèn từ một khách hàng ở xa mà tôi cần gửi dữ liệu qua http.
Tôi có thể sử dụng một cách chính xác getPerformances() với một httpClientapi/performances?date={0}MVC 4 Web Api Post

Tôi muốn hỏi nếu postPorformances() implemntation tôi bên PerformancesController của tôi là corrrect và nếu nó là làm thế nào để gọi nó là từ một khách hàng?

Đây là triển khai thực hiện của tôi:

public class PerformancesController : ApiController 
    { 
     // GET api/performances 
     public IEnumerable<Performance> getPerformances(DateTime date) 
     { 
      return DataProvider.Instance.getPerformances(date); 
     } 

     public HttpResponseMessage postPerformances(Performance p) 
     { 
      DataProvider.Instance.insertPerformance(p); 
      var response = Request.CreateResponse<Performance>(HttpStatusCode.Created, p); 
      return response; 
     } 
    } 
public class Performance { 
    public int Id {get;set;} 
    public DateTime Date {get;set;} 
    public decimal Value {get;set;} 
} 

Tôi đã thử cái này nhưng tôi lưu ý chắc chắn:

private readonly HttpClient _client; 
    string request = String.Format("api/performances"); 
    var jsonString = "{\"Date\":" + p.Date + ",\"Value\":" + p.Value + "}"; 
    var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json"); 
    var message = await _client.PutAsync(request, httpContent); 

Trả lời

10

Bạn có thể sử dụng HttpClient gọi này phương pháp:

using (var client = new HttpClient()) 
{ 
    client.BaseAddress = new Uri("http://example.com"); 
    var result = client.PostAsync("/api/performances", new 
    { 
     id = 1, 
     date = DateTime.Now, 
     value = 1.5 
    }, new JsonMediaTypeFormatter()).Result; 
    if (result.IsSuccessStatusCode) 
    { 
     Console.writeLine("Performance instance successfully sent to the API"); 
    } 
    else 
    { 
     string content = result.Content.ReadAsStringAsync().Result; 
     Console.WriteLine("oops, an error occurred, here's the raw response: {0}", content); 
    } 
} 

Trong ví dụ này tôi đang sử dụng phương thức chung PostAsync<T> cho phép tôi gửi bất kỳ đối tượng nào làm tham số thứ hai và chọn định dạng loại phương tiện. Ở đây tôi đã sử dụng một đối tượng ẩn danh bắt chước cấu trúc giống như mô hình Performance trên máy chủ và JsonMediaTypeFormatter. Tất nhiên bạn có thể chia sẻ mô hình Performance này giữa máy khách và máy chủ bằng cách đặt nó vào một dự án hợp đồng để các thay đổi trên máy chủ cũng sẽ được tự động phản ánh trên máy khách.

Nhận xét bên: Quy ước đặt tên C# quy định rằng tên phương thức phải bắt đầu bằng chữ hoa. Vì vậy, getPerformances phải là GetPerformances hoặc thậm chí tốt hơn GetpostPerformances phải là PostPerformances hoặc thậm chí tốt hơn Post.

+0

Nếu cuộc gọi ap/biểu diễn mất nhiều thời gian, bạn có thể muốn đặt ứng dụng khách.Thời gian chờ trước khi thực hiện cuộc gọi – BlackTigerX

Các vấn đề liên quan