Pierre Nortje Pierre Nortje - 3 months ago 19
ASP.NET (C#) Question

How to POST a DateTime value to a Web API 2 controller

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?

Answer

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"