I have an example controller:
[RoutePrefix("api/Example")]
public class ExampleController : ApiController
{
[Route("Foo")]
[HttpGet]
public string Foo([FromUri] string startDate)
{
return "This is working";
}
[Route("Bar")]
[HttpPost]
public string Bar([FromBody] DateTime startDate)
{
return "This is not working";
}
}
When I issue a GET request to: http://localhost:53456/api/Example/Foo?startDate=2016-01-01 it works.
When I POST to http://localhost:53456/api/Example/Bar I receive a HTTP/1.1 400 Bad Request error.
This is my POST data:
{
"startDate":"2016-01-01T00:00:00.0000000-00:00"
}
What am I doing wrong?
You can't post non-objects directly, you need to wrap them in side an object container when using FromBody.
[RoutePrefix("api/Example")]
public class ExampleController : ApiController
{
[Route("Foo")]
[HttpGet]
public string Foo([FromUri] string startDate)
{
return "This is working";
}
[Route("Bar")]
[HttpPost]
public string Bar([FromBody] BarData data)
{
return "This is not working";
}
}
public class BarData{
public DateTime startDate {get;set;}
}
The other way it could work is if you form-encode the value like this using the = symbol (note you are sending it as a non-object, the curly braces have been removed).
"=2016-01-01T00:00:00.0000000-00:00"
Try just POSTing:
{
"2016-01-01T00:00:00.0000000-00:00"
}
Specifying the property name would mean your endpoint would need to accept an object with a property named startDate. In this case you only want to pass a DateTime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With