Software Architect
Software Architect

Reputation: 141

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 web site with this:

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();
}

Upvotes: 0

Views: 123

Answers (1)

maxbeaudoin
maxbeaudoin

Reputation: 6966

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.

Upvotes: 1

Related Questions