Asp.net

如何將 DateTime 值發佈到 Web API 2 控制器

  • December 20, 2017

我有一個範例控制器:

[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它有效。

當我發佈到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"

引用自:https://stackoverflow.com/questions/39004405