0

Im using this line to consume the API post method

 var postTask = client.PostAsJsonAsync("AgregarNegocio", new StringContent(JsonConvert.SerializeObject(model).ToString(), Encoding.UTF8, "application/json"));

however when the API method is hit

public IActionResult AgregarNegocio([FromBody]NegocioViewModel model) 

all the properties in model are null... i already tried with and without [FromBody] and other solutions but none has worked yet, any suggestions?, thanks!

mj1313
  • 7,930
  • 2
  • 12
  • 32
  • because you are not posting json... you are posting a string... PostAsJsonAsync should convert your object to json... you dont need to convert it yourself so I am pretty sure what you are sending does not match NegocioViewModel... What you need to do is get rid of the StringContent and everything in it and just pass your model as is – Jonathan Alfaro Mar 16 '21 at 04:18
  • @JonathanAlfaro thanks for responding, HttpClient does not give me a way to send my NegocioViewModel object as is, do you know how i could do it?, thanks! – EMILIO ZARATE Mar 16 '21 at 04:23
  • You are already using PostAsJsonAsync it should allow you to send an object – Jonathan Alfaro Mar 16 '21 at 12:45
  • if you mean something like this var postTask = client.PostAsJsonAsync("AgregarNegocio", model); thats the first code i wrote and it didnt even hit the web api, any possible reason? RequestUri: '.../AgregarNegocio', Version: 1.1, Content: System.Net.Http.ObjectContent`1[..NegocioViewModel], Headers: { Request-Id: |9d11fffd-49d88077a7dffa67.1. Transfer-Encoding: chunked Content-Type: application/json; charset=utf-8 }} – EMILIO ZARATE Mar 16 '21 at 14:05
  • That is how to you send it. Also you need to make sure your Action is HttpPost in the backend – Jonathan Alfaro Mar 16 '21 at 14:34
  • this is my api method [HttpPost] [Route("AgregarNegocio")] public IActionResult AgregarNegocio([FromBody]NegocioViewModel model) and by calling it like this: var postTask = client.PostAsJsonAsync("AgregarNegocio", model); is not even hit as i previously mentioned, only way to hit it is: var postTask = client.PostAsJsonAsync("AgregarNegocio", new StringContent(JsonConvert.SerializeObject(model).ToString(), Encoding.UTF8, "application/json")); but model properties are null as originally posted in the question – EMILIO ZARATE Mar 16 '21 at 16:36
  • you might need to add the Header... I am going to post an answer on how I do it – Jonathan Alfaro Mar 16 '21 at 17:13

4 Answers4

0

Try to use PostAsync instead of PostAsJsonAsync

var postTask = await client.PostAsync("AgregarNegocio", new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json"));
mj1313
  • 7,930
  • 2
  • 12
  • 32
  • i tried that before, is not even hitting the web api, it throws "Internal Server Error" RequestMessage = {Method: POST, RequestUri: '.../AgregarNegocio', Version: 1.1, Content: System.Net.Http.StringContent, Headers: { Request-Id: |d040ca6a-4f2bc1853b68983e.1. Content-Type: application/json; charset=utf-8 Content-Len... – EMILIO ZARATE Mar 16 '21 at 14:01
0

You can use the HttpClient extension method : https://learn.microsoft.com/en-us/previous-versions/aspnet/hh944682(v=vs.118)

PostAsJsonAsync( this HttpClient client, string requestUri, T value )

var postTask = client.PostAsJsonAsync<NegocioViewModel>("AgregarNegocio", model);
Houssem Romdhani
  • 332
  • 1
  • 11
  • same as answer above, i tried that at the beginning and its not even hitting the web api, {Method: POST, RequestUri: '.../AgregarNegocio', Version: 1.1, Content: System.Net.Http.ObjectContent`1[....NegocioViewModel], Headers: { Request-Id: |9d11fffd-49d88077a7dffa67.1. Transfer-Encoding: chunked Content-Type: application/json; charset=utf-8 }} – EMILIO ZARATE Mar 16 '21 at 14:04
0

You can use PostAsync but also do not forget about using HttpClient in right way as i described in this article.

A Programmer
  • 625
  • 8
  • 30
0

You need to construct your http client like this:

_client = new HttpClient { BaseAddress = new Uri("your http://my base url goes here"), 
                           Timeout = new TimeSpan(0, 0, 0, 0, -1) };

_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(
                     new MediaTypeWithQualityHeaderValue("application/json"));//add json header
//_client.DefaultRequestHeaders.Add("Bearer", "some token goes here");

and you need to call your method like this:

var postTask = await _client.PostAsJsonAsync("AgregarNegocio", model);

make sure you call "await" on it because it is async.

NOTES:

Notice that I added MediaTypeWithQualityHeaderValue to indicate that it is json.

Also using Route usually is not a good idea... It is better to use HttPost("MyRoute") because it combined the ControllerName + Route. But it is up to you.

Jonathan Alfaro
  • 4,013
  • 3
  • 29
  • 32
  • this works when im sending only text, what if my model contains an IFormFile? when trying to send this property in order to upload an image in the form on the webapi side it throws an error, any advise? thanks for your answers! – EMILIO ZARATE Mar 16 '21 at 17:50
  • this are some of the properties this class contains public long Id { get; set; } public string Nombre { get; set; } public string Descripcion { get; set; } public IFormFile Logo { get; set; } when sending the IFormFile it wont work, any suggestion? – EMILIO ZARATE Mar 16 '21 at 17:57
  • IFormFile cannot be sent in Json because it is some kind of stream.... What you have to do is upload the file in separate call or on a form post. Once you have the IFormFile you have to turn it into a byte[] and that can be the Logo property like public byte[] Logo {get;set;} – Jonathan Alfaro Mar 16 '21 at 19:08
  • So basically IFormFile cannot be sent as json, First it needs to be converted to a byte[] – Jonathan Alfaro Mar 16 '21 at 19:09
  • 1
    got it, actually i was doing that (uploading the image on web application site and getting the bytes from there) but i was trying to see if it was possible to send the IFormFile within the ViewModel to the WebAPI, anyway you helped me a lot, i appreciate man, thanks! – EMILIO ZARATE Mar 16 '21 at 20:58
  • Man i was able to send the IFormFile by following this way: https://stackoverflow.com/questions/61098341/asp-net-core-post-form-data-iformfile-with-viewmodel-using-httpclient you might check it in case you need it later, thanks again! – EMILIO ZARATE Mar 16 '21 at 21:12