2013-03-04 130 views
5

我想從遠程客戶端插入,因爲我需要通過http發送數據。
我可以用httpClientapi/performances?date={0}MVC 4 Web Api Post

我想問一下,如果我的postPorformances() implemntation我PerformancesController裏面corrrect正確使用getPerformances(),如果它是如何從一個客戶端調用?

這是我實現:

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

我已經試過這一個,但我注意到肯定:

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

回答

10

您可以使用HttpClient來調用這個方法:

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

在這個例子中,我使用通用PostAsync<T>方法,允許我發送任何對象作爲第二個參數並選擇媒體類型格式化程序。在這裏,我使用了一個匿名對象,模仿與服務器上的Performance型號和JsonMediaTypeFormatter型號相同的結構。您當然可以在客戶端和服務器之間共享這個Performance模型,方法是將它放在合同項目中,這樣服務器上的更改也會自動反映在客戶端上。

備註:C#命名約定規定方法名稱應該以大寫字母開頭。所以getPerformances應該是GetPerformances或甚至更好GetpostPerformances應該是PostPerformances或甚至更好Post

+0

如果ap /演出電話需要很長時間,您可能需要設置客戶端。在撥打電話之前超時 – BlackTigerX 2015-11-19 23:46:23