Search code examples
c#asp.net-mvcasp.net-web-apiasp.net-web-api2asp.net-web-api-routing

Pass List object to C# Web Api POST


I am trying to pass a List to my Web API but I keep getting a null value. I am converting the list in to a string before passing it to the API. Any ideas how can I bind it correctly?

public async Task<ReturnViewModel> ModContactsAsync(List<ContactsDTO> Contacts)
 {
     ReturnViewModel vm = new ReturnViewModel();

    var postContactsUri = new UriBuilder(AppConfig.ServiceUrlBase);

    //Converts object into a string
    var jsonObject = new JavaScriptSerializer().Serialize(Contacts);


    postContactsUri.Path = string.Format(POST_CONTACTS_API_PATH, jsonObject);
    //Calls API
    var response = await _httpClient.PostAsync(postContactsUri.ToString());

    return vm;
}

POST - API CALL List prod is null

[HttpPost]
[Route("contacts/Save")]
[ResponseType(typeof(ReturnMessage))]
public async Task<IHttpActionResult> ModContacts([FromBody] List<ContactsDTO> prods)
{
    try
    {
        await Task.Delay(10);

        return Ok();
    }
    catch (Exception ex)
    {
        throw new PropertyPortalWebApiException(HttpStatusCode.InternalServerError, "Contact information does not exist.", ex);
    }
  }

Solution

  • I figured out the issue. Just add the Contacts object to the PostAsync to the second parameter and voila. You don't need to convert the object to JSON.

    public async Task<ReturnViewModel> ModContactsAsync(List<ContactsDTO> Contacts)
    {
        ReturnViewModel vm = new ReturnViewModel();
    
        var postContactsUri = new UriBuilder(AppConfig.ServiceUrlBase);
    
        postContactsUri.Path = string.Format(POST_CONTACTS_API_PATH, jsonObject);
        //Add Contacts to second parameter
        var response = await _httpClient.PostAsync(postContactsUri.ToString(), Contacts);
    
    return vm;
    

    }