MVC 4 Web Api 发布文章

6
我希望能进行远程客户端数据的插入,因此需要通过http发送数据。
我可以使用httpClientapi/performances?date={0}以正确地调用getPerformances()
我想询问我的PerformancesControllerpostPerformances()的实现是否正确,如果正确,如何从客户端调用它?
这是我的实现内容:
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);
1个回答

11

您可以使用 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或者更好的Get,而postPerformances应该是PostPerformances或者更好的Post

如果ap/performances调用需要很长时间,您可能希望在调用之前设置client.Timeout。 - BlackTigerX

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接