MVC 4 Web Api Post

gsm*_*ida 6 c# asp.net httpclient asp.net-web-api

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

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

这是我的实现:

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;
        }
    }
Run Code Online (Sandbox Code Playgroud)
public class Performance {
    public int Id {get;set;}
    public DateTime Date {get;set;}
    public decimal Value {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

我试过这个,但我要注意:

  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);
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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