我有一个示例控制器:
[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";
}
}
当我向:http://localhost:53456/api/Example/Foo?startDate=2016-01-01
发出GET请求时,它有效。
当我发布到http://localhost:53456/api/Example/Bar
时,我收到HTTP/1.1 400 Bad Request
错误。
这是我的POST数据:
{
"startDate":"2016-01-01T00:00:00.0000000-00:00"
}
我究竟做错了什么?
您不能直接发布非对象,在使用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;}
}
它可以工作的另一种方式是使用=
符号对这样的值进行形式编码(请注意,您将其作为非对象发送,花括号已被删除)。
"=2016-01-01T00:00:00.0000000-00:00"
尝试发布:
{
"2016-01-01T00:00:00.0000000-00:00"
}
指定属性名称意味着您的端点需要接受具有名为startDate
的属性的对象。在这种情况下,你只想传递一个DateTime
。
提交的日期格式很重要,具体取决于您的客户端库。它必须如下所示(原始有效负载中的引号):
"2015-05-02T00:00:00"
没有大括号,没有属性名称。从代码和/或客户端库传输的格式取决于您是发送javascript日期还是字符串表示形式。所以,适当调整提交代码......