3

When I make a JSON call from AngularJS to my WebApi controller via a GET request, my dates come through to my model as 'Local' kind. This is fine and how I want it to work.

However, when I change the method to POST (on both the WebApi controller and my AngularJS client side code), the dates are an hour out because the DateTime kind is now UTC. The dates are serialized via .toJSON() before being sent and everything looks the same via Chrome's network inspection when looking at the GET and POST requests.

How can I keep the DateTime Kind's consistent across POST and GET requests so that they are always Local?

Edit #1:

Angular JS Call:

            var params = {
                DateFrom: detail.from.toJSON(),
                DateTo: detail.to.toJSON(),
                Filters: detail.filters
            };

            return http.post(window.urls.apiGetAllErrorsGraphData, params);

In my current example, the value of params.DateFrom = "2014-04-30T23:00:00.000Z", detail.from = 01/05/2014 as a JS Date object.

'http.post' in this case is an Angular service that I wrote that basically wraps HTTP calls.

.NET WebAPI Controller

    [POST("api/errors/chart")]
    [HttpPost]
    [HttpOptions]
    public IHttpActionResult GetAllErrorsGraphData([FromBody]AllErrorChartDetails details)
    {
        var results = chartDataService.GenerateAllErrorsData(details.DateFrom, details.DateTo, details.Filters);

        return Ok(results.Select(x => new { date = x.Key, errors = x.Value }));
    }

I'm using AttributeRouting if you're curious what the attributes are over the method.

Tom
  • 2,321
  • 2
  • 18
  • 29

1 Answers1

0

Can you not just convert the DateTime object when you retrieve it to whatever format you need?

DateTime json = yourJsonMethod();
json = json.ToLocalTime();
Nathan Brown
  • 311
  • 1
  • 3
  • 12
  • I could I guess but this is kinda hacky don't you think? I'll have to do this or something similar across all my methods where I've needed to convert my methods from GET to POST. – Tom Sep 08 '14 at 16:26
  • Hacky isn't always a bad thing :-) although if you have several methods where this code is used it may be a hassle. Could also just do it inline: `details.DateFrom.ToLocalTime();` [See here](http://stackoverflow.com/questions/22581138/passing-utc-datetime-to-web-api-httpget-method-results-in-local-time); looks like there may also be a way to make the conversion "transparent" so maybe you don't need the method every single time...(See Sean Fausett's answer) – Nathan Brown Sep 08 '14 at 16:37
  • I couldn't seem to get Sean Fausett's solution to work for me, the dates kept coming in as Utc. I can't help feel that this is a bug in the framework, I can't see a reason why you'd want the DateTime Kind to differ between the various HTTP methods. – Tom Sep 09 '14 at 08:14