Passing datetime from angular $ http.get request to Web API 2 controller

I have a web API 2 controller:

[HttpGet]
[Route("api/MyRoute/{date:datetime}")]
public IHttpActionResult Get(DateTime date)
{
    return Ok(date);
}

      

And the angular $ http call:

$http.get("/api/MyRoute/" + new Date());

      

It doesn't work, I am getting 404 error.

I also get this error after 404:

XMLHttpRequest cannot load http: // localhost: 2344 / api / MyRoute / 2017-06-28T00: 00: 00.000Z . Pre-flight request response does not pass access control check. There is no "Access-Control-Allow-Origin" header on the requested resource.

But if I change the parameter to anything other than the date it works on.

I've tried new Date (). toISOString () and does the same.

So how do I pass the date from angular to the web API controller?

+3


source to share


1 answer


The problem is related to the datetime specification in the routing attribute. The solution was to just remove it and define the route like this

[HttpGet]
[Route("api/MyRoute")]
public IHttpActionResult Get(DateTime date)
{
    return Ok(date);
}

      



And then call the api from the client

$http.get("/api/MyRoute?date=" + new Date().toISOString());

      

0


source







All Articles