Passing DateTimeOffset as WebAPI query string

.net, asp.net-web-api, c#

Solution

The problem is being described exactly by the 400 response message, although it could have been more clear. The route, as defined by the attribute, only expects a parameter id, but the Delete method expects another parameter called date.

If you want to provide this value using the query string, you'll need to make that parameter nullable, by using "DateTimeOffset?", which would also transform it into an optional parameter. If the date is a required field, consider adding it to the route, like:

[Route("api/values/{id}/{date}")]

OK, ignore what I typed above, it's just a formatting problem. Web API has trouble figuring out the culture needed to parse the given value, but if you try to pass on DateTimeOffset using a JSON format in the query string, like 2014-05-06T22:24:55Z, that should work.

Problem

I've got a WebAPI action that looks like so: ``` [Route("api/values/{id}")] public async Task<HttpResponseMessage> Delete(string id, DateTimeOffset date) { //do stuff } ``` But when I invoke this from a `HttpClient` instance, making a URL like: ``` string.Format("http://localhost:1234/api/values/1?date={0}", System.Net.WebUtility.UrlEncode(DateTimeOffset.Now.ToString())); // -> "http://localhost:1234/api/values/1?date=17%2F02%2F2015+7%3A18%3A39+AM+%2B11%3A00" ``` I get a `400` response back saying that the non-nullable parameter `date` does not exist. I've also tried adding the `[FromUri]` attribute to the parameter but it still doesn't map through. If I change it to be `DateTimeOffset?` I can see it is left as null and looking at `Request.RequestUri.Query` the value is there, just not mapped. Finally I tried not doing a `WebUtility.UrlEncode` and it made no different.

Original source

Related problems