C
C#•8mo ago
Mario K.

.NET 6 web api - HttpClient.PostAsync not hitting HttpPost in controller

Hello ! I have a controller with [HttpPost] method, but httpclient.postasinc does not hit it. Instead it returns 400 (bad request).... DeleteAsync and GetAsync properly hit corresponding [HttpDelete] and [HttpGet] methods in the controller ... Any suggestions ?
8 Replies
Angius
Angius•8mo ago
What are you sending and what do you expect to receive, exactly? Delete and Get have no body, so it cannot be malformed But in case of a Post, if the endpoint expects JSON but you're sending form data, it's not gonna work
Mario K.
Mario K.OP•8mo ago
These are the code: var content = new StringContent(JsonConvert.SerializeObject(customer), Encoding.UTF8, "application/json"); var httpResponse = await _client.PostAsync(RequestUri, content); and in controller: // POST: api/customers [HttpPost] [Consumes("application/json")] public async Task<ActionResult> Post([FromBody] CustomerModel value) {

//throw new NotImplementedException(); } but the code in controller never gets hit .... and API returns bad request it is -NET 6
Angius
Angius•8mo ago
Try just doing
var response = await _client.PostAsJsonAsync(RequestUri, customer);
var response = await _client.PostAsJsonAsync(RequestUri, customer);
Without encoding the content manually With Netwonsoft to boot
Mario K.
Mario K.OP•8mo ago
I'll try, but that code is not to be changed ...:) I changed, but controller is still not hit...
Hass
Hass•8mo ago
your CustomerModel does not match what you are sending to the method, probably try accepting/posting a string and see if it hits the controller
Mario K.
Mario K.OP•8mo ago
OK, I'll try YESSSS !
Hass
Hass•8mo ago
nice 😄 now you need to check what is different between what you are sending from what your controller is expecting
Mario K.
Mario K.OP•8mo ago
customer is however StringCintent StringContent .... accepting StringContent again does not work ,,,, and accepting string results in accepted string being null ...
Want results from more Discord servers?
Add your server