MVC 4 Web Api Post

我想从远程客户端插入,因为我需要通过http发送数据。
我可以正确使用getPerformances()httpClient api/performances?date={0}

我想问一下我的postPorformances()实现是否正确以及是否如何从客户端调用它?

这是我的实施:

 public class PerformancesController : ApiController { // GET api/performances public IEnumerable getPerformances(DateTime date) { return DataProvider.Instance.getPerformances(date); } public HttpResponseMessage postPerformances(Performance p) { DataProvider.Instance.insertPerformance(p); var response = Request.CreateResponse(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); 

您可以使用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方法,允许我发送任何对象作为第二个参数,并选择媒体类型格式化程序。 在这里,我使用了一个匿名对象,它模仿与服务器和JsonMediaTypeFormatter上的Performance模型相同的结构。 您当然可以通过将它放在合同项目中来在客户端和服务器之间共享此Performance模型,以便服务器上的更改也会自动反映在客户端上。

旁注:C#命名约定规定方法名称应以大写字母开头。 所以getPerformances应该是GetPerformances甚至更好GetpostPerformances应该是PostPerformances甚至更好Post