2013-03-04 110 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