这是我的webapi post请求
[HttpPost]
[Route("Create/{id}")]
public async Task<IActionResult> CreateContact(Guid id, string email, string fullName)
{
// code removed for brevity
}
我如何张贴contact
对象到webapi?这是我的客户端。
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://localhost:123");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var contact = new Contact() { Id = 12345, Email = "test@gmail.com", FullName = "John" };
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/Contact/Create/{contact.Id}", contact);
if (response.IsSuccessStatusCode)
{
}
else
{
}
}
不确定这是否是最好的,但它工作。在Route
属性
[HttpPost]
[Route("Create/{id}/{email}/{fullName}")]
public async Task<IActionResult> CreateContact(Guid id, string email, string fullName)
{
// code removed for brevity
}
,然后在httpclient
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/Contact/Create/{contact.Id}/{contact.Email}/{contact.FullName}", contact);
大家好,在WPI中使用[FromBody]。您可以将Contact作为对象发布
[HttpPost]
[Route("Create/{contact}")]
public async Task<IActionResult> CreateContact([FromBody]Contact contact)
{
// code removed for brevity
}
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://localhost:123");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var contact = new Contact() { Id = 12345, Email = "test@gmail.com", FullName = "John" };
var contactJson = JsonConvert.SerializeObject(contact);
var stringContent = new StringContent(contactJson , UnicodeEncoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync($"/api/Contact/Create/", stringContent);
if (response.IsSuccessStatusCode)
{
}
else
{
}
}