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:
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();
}
CodePudding user response:
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
.