Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cannot send post request to my API controller with HttpClient

I am working on communication between API <-> webAPP via HttpClient.

This is my API controller:

        [HttpPut, Route("voipport/{newPort}")]
    public async Task<IActionResult> PutVoipPort(int newPort)
    {
        try
        {
            await _repository.ChangePort(newPort);
            await _repository.AddNewRecord("PutVoipPort", "Success");
            return Ok();
        }
        catch(Exception exception)
        {
            return BadRequest(exception.Message);
        }

    }

this is fired from website with this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        public async Task VOIPChangePort(int newPort)
    {
        var json = JsonConvert.SerializeObject(newPort);
        var data = new StringContent(json,Encoding.UTF8,"application/json");
        var result = await _httpClient.PutAsync("voipport/{newPort}", data);
        result.EnsureSuccessStatusCode();
        Console.WriteLine(result);
    }

and this is the result:

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
  Date: Fri, 25 Nov 2022 18:15:08 GMT
  Server: Kestrel
  Transfer-Encoding: chunked
  Content-Type: application/problem+json; charset=utf-8
}}

I dont know why i cannot call my controller method.

##UPDATE
this is solution

public async Task VOIPChangePort(int newPort)
{
    var result = await _httpClient.PutAsync($"voipport/{newPort}", null);
    result.EnsureSuccessStatusCode();
}

>Solution :

newPort seems to be part of the route and not the body. Don’t pass any JSON.

You’re calling voipport/{newPort} when you should be templating that string with the actual int newPort, like this: voipport/65000.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading