Reputation: 13479
Please consider these two Web API methods:
[HttpPost]
[Route(getdata1)]
public IActionResult Getdata1()
{
return Ok("Hello")
}
[HttpPost]
[Route(getdata2)]
public IActionResult Getdata2([FromBody] string name)
{
return Ok("Hello" + name)
}
When I call first method with the code shown here, it is ok and I get Hello
message:
String url: "https://localhost:1234/api/getdata1";
var client = HttpClient();
var Response = client.PostAsync(url, null).Result;
if (Response.IsSuccessStatusCode)
{
Console.Write(Response.Content.ReadAsStringAsync().Result);
}
else
{
Console.Write(Response.StatusCode);
}
But when I call the second method with the code shown, I get BadRequest
error:
String url: "https://localhost:1234/api/getdata2";
var tmp = new { name = "Test" }
var json = JsonSerializer.Serialize(tmp);
var Parameter = new StringContent(json, Encoding.UTF8, "application/json")
var client = HttpClient();
var Response = client.PostAsync(url, Parameter).Result;
if (Response.IsSuccessStatusCode)
{
Console.Write(Response.Content.ReadAsStringAsync().Result);
}
else
{
Console.Write(Response.StatusCode);
}
Please help me.
Upvotes: 1
Views: 42
Reputation: 51420
You are posting the JSON object to the "Getdata2" API. The API action's argument should be an object/class type instead of string.
[HttpPost]
[Route(getdata2)]
public IActionResult Getdata2([FromBody] GetDataInput model)
{
return Ok("Hello" + model.Name);
}
public class GetDataInput
{
public string Name { get; set; }
}
Upvotes: 1