简体   繁体   中英

Post data to the WebApi which its parameter is not complex object using Httpclient

This is my webapi post request

    [HttpPost]
    [Route("Create/{id}")]
    public async Task<IActionResult> CreateContact(Guid id, string email, string fullName)
    {
        // code removed for brevity
    }

How do I post contact object over to the webapi? This is what I have in the client.

   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
            {
         
            }
        }

Not sure if this is the best but it works. Add more parameter at the Route attribute

[HttpPost]
[Route("Create/{id}/{email}/{fullName}")]
public async Task<IActionResult> CreateContact(Guid id, string email, string fullName)
{
    // code removed for brevity
}

and then at the httpclient

 HttpResponseMessage response = await client.PostAsJsonAsync($"/api/Contact/Create/{contact.Id}/{contact.Email}/{contact.FullName}", contact);

Hi there Use [FromBody] in your WPI. The you can post the Contact as an object

    [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
            {
         
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM