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);
}
}
You should simply search and understand GET/POST difference and how to post with HttpClient.
First you are adding your content in URL and trying to post it with HttpClient.
var response = await _httpClient.PostAsync(postContactsUri.ToString());
And then in your API you are reading the object FromBody which has been passed in URL.
public async Task<IHttpActionResult> ModContacts([FromBody] List<ContactsDTO> prods)
The signature of PostAsync method is
public Task PostAsync(Uri uri, HttpContent content)
So you should pass URL in first parameter and your list object in form of HttpContent as second parameter.
Or you can use PostAsJsonAsync extension method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With