Good morning,
I have a big problem with routing (I guess) for http Post calls. I use .Net 6.
I have the following call which works fine:
HttpResponseMessage response1 = await client.GetAsync("http://localhost:6000/api/" + "Utilisateur/AjouterUtilisateur1/" + "Machaine");
On the UserController class, I have the following code:
[Route("api/[controller]")]
[ApiController]
public class UtilisateurController : Controller
[HttpPost("AjouterUtilisateur1/{jsonArgs}")]
public ActionResult<string> AjouterUtilisateur1(string jsonArgs)
{ … }
That works well. Now I would like to do a Post instead of the Get. So on the caller, I have the code:
HttpContent httpContent1 = new StringContent("MaChaine", Encoding.UTF8);
HttpResponseMessage response1 = await client.PostAsync("http://localhost:6000/api/" + "Utilisateur/AjouterUtilisateur1", httpContent1);
And on the server, I have the code:
[Route("api/[controller]")]
ApiController]
public class UtilisateurController : Controller
[HttpPost("AjouterUtilisateur1")]
public ActionResult<string> AjouterUtilisateur1(string jsonArgs)
{ … }
The class constructor is well executed but that's it. This gives me the following error in response1 (at the caller level):
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers: { Date: Fri, 14 Jul 2023 17:37:53 GMT Server: Kestrel Transfer-Encoding: chunked Content-Type: application/problem+json; charset=utf-8 }}
Thanks for your help !
Can you help me find my error please?
A bad request means that you are not sending the payload as its required by the backend, so you need to make the below changes.
you can send the JSON string like the one below.
and If you have a dto object and you can serialize it to a JSON string and use the
PostAsJsonAsync
to send the JSON.