Reputation: 526
Using postman, am trying to post "city" and "country" data.
URL: http://localhost:8080/api/Sample/SendData
RequestBody: {"city": "abc","country": "xyz"}
Headers: Content-Type: application/json
But am unable to retrieve the data instead getting nulls as show below. By encapsulating the properties (city, country) into a model, I am able to see the data.
Below is the code am using
[AllowAnonymous]
[ApiController]
public class SampleController : ControllerBase
{
private readonly ILogger<SampleController> _logger;
public SampleController(ILogger<SampleController> logger)
{
_logger = logger;
}
[HttpPost]
[Route("api/Sample/SendData")]
public ActionResult SendData(string city, string country)
{
try
{
if (ModelState.IsValid)
{
//return
return Ok("Success");
}
else
{
throw new Exception("error");
}
}
catch (Exception ex)
{
//return
return BadRequest(Convert.ToString(ex));
}
}
}
Note: I want to send the data using request body and not through query string as the data am going to pass eventually be larger.
Upvotes: 0
Views: 380
Reputation: 6130
It won't work with individual parameters. When you're using datatype json, the asp.net controller will always assume it's an object you're sending.
If you want individual parameters you could remove the json request header and replace it with text/plain
and change your request body to key-value.
There's a similar question here but you would need to install newtonsoftjson nuget package. You'll only get 1 string though, which is the whole json file, then you'll be deserializing it to an object when it gets to the controller.
POST Json without model and Ajax
Upvotes: 1