.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
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
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
//throw new NotImplementedException(); } but the code in controller never gets hit .... and API returns bad request it is -NET 6
Try just doing
Without encoding the content manually
With Netwonsoft to boot
I'll try, but that code is not to be changed ...:)
I changed, but controller is still not hit...
your
CustomerModel
does not match what you are sending to the method, probably
try accepting/posting a string
and see if it hits the controllerOK, I'll try
YESSSS !
nice 😄
now you need to check what is different between what you are sending from what your controller is expecting
customer is however StringCintent
StringContent .... accepting StringContent again does not work ,,,,
and accepting string results in accepted string being null ...