我有一个示例 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";
}
}
当我向以下位置发出 GET 请求时:http://localhost:53456/api/Example/Foo?startDate=2016-01-01
它有效。
当我 POST 到 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"
关于asp.net - 如何将 DateTime 值发布到 Web API 2 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39004405/