如何 POST 一个日期时间值到 Web API 2 控制器
How to POST a DateTime value to a Web API 2 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"
}
我做错了什么?
尝试只发帖:
{
"2016-01-01T00:00:00.0000000-00:00"
}
指定 属性 名称意味着您的端点需要接受一个名为 startDate
的 属性 对象。在这种情况下,您只想传递 DateTime
.
你不能直接post非对象,你需要在使用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"
日期的提交格式很重要,取决于您的客户端库。它必须看起来像这样(原始主体负载中的引号):
"2015-05-02T00:00:00"
没有大括号,没有 属性 名字。从您的代码 and/or 客户端库传输的格式将取决于您发送的是 javascript 日期还是日期的字符串表示形式。因此,适当调整提交代码...
我有一个示例控制器:
[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"
}
我做错了什么?
尝试只发帖:
{
"2016-01-01T00:00:00.0000000-00:00"
}
指定 属性 名称意味着您的端点需要接受一个名为 startDate
的 属性 对象。在这种情况下,您只想传递 DateTime
.
你不能直接post非对象,你需要在使用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"
日期的提交格式很重要,取决于您的客户端库。它必须看起来像这样(原始主体负载中的引号):
"2015-05-02T00:00:00"
没有大括号,没有 属性 名字。从您的代码 and/or 客户端库传输的格式将取决于您发送的是 javascript 日期还是日期的字符串表示形式。因此,适当调整提交代码...