我想从远程客户端进行插入,因为我需要通过 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;
}
}
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<T>
方法允许我发送任何对象作为第二个参数并选择媒体类型格式化程序。在这里,我使用了一个匿名对象,模仿与您相同的结构Performance
服务器上的模型和JsonMediaTypeFormatter
。你当然可以分享这个Performance
通过将其放置在合同项目中,在客户端和服务器之间建立模型,以便服务器上的更改也会自动反映在客户端上。
附注:C# 命名约定规定方法名称应以大写字母开头。所以getPerformances
应该GetPerformances
甚至更好Get
and postPerformances
应该PostPerformances
甚至更好Post
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)