7

I have a web API 2 controller:

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

And an angular $http get call:

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

This doesn't work, I get a 404 error.

I also get this error after the 404:

XMLHttpRequest cannot load http://localhost:2344/api/MyRoute/2017-06-28T00:00:00.000Z. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

But if I change the parameter to anything but a date it works.

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

So how do I pass a date from Angular to a Web API controller?

2
  • Just tried. Same result. Commented Jun 28, 2017 at 12:42
  • Try '$http.get("/api/MyRoute/" + encodeURIComponent(new Date()))' or '$http.get("/api/MyRoute/" + encodeURIComponent(new Date().toISOstring()))' Commented Jun 29, 2017 at 1:34

1 Answer 1

9

The problem seems to be with the datetime specification in the routing attribute. The solution was to just remove it and define the route as this

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

And then call the api from the client by

$http.get("/api/MyRoute?date=" + new Date().toISOString());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.