Steve
Steve

Reputation: 4453

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 = "[email protected]", FullName = "John" };
            HttpResponseMessage response = await client.PostAsJsonAsync($"/api/Contact/Create/{contact.Id}", contact);

            if (response.IsSuccessStatusCode)
            {
                
            }
            else
            {
         
            }
        }

Upvotes: 0

Views: 385

Answers (2)

Theo Koekemoer
Theo Koekemoer

Reputation: 228

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 = "[email protected]", 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
            {
         
            }
        }

Upvotes: 0

Steve
Steve

Reputation: 4453

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);

Upvotes: 1

Related Questions