Reputation: 489
I have a legacy ASP.NET WebForms application that collects a date value in a textbox and since we don't explicitly specify a time it defaults to midnight. For example, if we enter today's date, the DateTime value is 12/08/2017 00:00:00.
I send the data to our WebApi and when I debug the controller and inspect the incoming data, that value will be read as 12/08/2017 07:00:00. Our local time zone is UTC-7:00. However, the client application passes the value 12/08/2017 00:00:00 right before sending it over. Something is performing a shift on the time and it appears to be compensating for the time zone.
Clearly I don't want this. I shouldn't have to add code in the API to shave off any time value in my DateTime data. What can be done about this? I've never seen this behavior before.
Here's the code that sends the data to the API:
public static void Update(Newsletter newsletter)
{
if (newsletter == null)
throw new ArgumentNullException(nameof(newsletter));
using (var client = WebApiUtils.GetConfiguredClient())
{
var uriString = $"Newsletters/{newsletter.ID}";
var requestUri = new Uri(uriString, UriKind.Relative);
using (var content = GenerateStringContent(newsletter))
{
using (var response = client.PutAsync(requestUri, content).Result)
{
response.EnsureSuccessStatusCode();
}
}
}
}
public static HttpClient GetConfiguredClient()
{
var uriString = GetWebApiUri(); // Read from web.config
var client = new HttpClient { BaseAddress = uriString };
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(JsonMediaType));
return client;
}
public static StringContent GenerateStringContent(object data)
{
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
var content = new StringContent(json, Encoding.UTF8, JsonMediaType);
return content;
}
My guess is that the serialization is doing the time zone shift but I don't know how to correct it if that's the case.
Upvotes: 1
Views: 4235
Reputation: 62213
If you want to treat all incoming / outgoing DateTime
instances as Utc by default in your Web API application then you can add this to your WebApiConfig.cs
file.
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
// other code unchanged
config.SetTimeZoneInfo(TimeZoneInfo.Utc);
}
}
Upvotes: 3