Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 591
Pierre Nortje Avatar asked Aug 17 '16 19:08

Pierre Nortje


2 Answers

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"
like image 106
Igor Avatar answered Sep 23 '22 18:09

Igor


Try just POSTing:

{
  "2016-01-01T00:00:00.0000000-00:00"
}

Specifying the property name would mean your endpoint would need to accept an object with a property named startDate. In this case you only want to pass a DateTime.

like image 30
hvaughan3 Avatar answered Sep 22 '22 18:09

hvaughan3