ASP.NET WebAPI XmlFormatter Missing UTC Offset for Dates
-
26-07-2021 - |
Pregunta
I have an ASP.NET WebAPI implementation that I am allowing clients to consume and request either XML or JSON formatting of the HTTP response. Some of the response objects include date/time values. I have been successful in getting the JSON response to include a proper ISO 8601 formatted date (including UTC time offset) by using code like:
Dim json As JsonMediaTypeFormatter = _
GlobalConfiguration.Configuration.Formatters.JsonFormatter
json.SerializerSettings.DateFormatHandling = _
Newtonsoft.Json.DateFormatHandling.IsoDateFormat
json.SerializerSettings.DateTimeZoneHandling = _
Newtonsoft.Json.DateTimeZoneHandling.Local
The JsonFormatter now gives me a date like this:
2008-11-03T14:14:00-05:00
However, the XmlFormatter gives me a date like:
2008-11-03T14:14:00
Notice the missing UTC time offset ("-05:00"). How do I get the XMLFormatter to give me the UTC time offset?
Solución
I believe I just figured this out myself.
When reading the dates from the SQL Server database (using an IDataReader) and the Enterprise Library Data Block, I need to use the Date.SpecifyKind method to tell what kind of date is being retrieved from the database.
Dim dateCreated As Date = _
Date.SpecifyKind(CDate(dbReader("DateCreated")), DateTimeKind.Local)
By doing this, I was also able to remove the JsonMediaTypeFormatter lines specified in my original question. So, now both XML and JSON send the date as:
2008-11-03T14:14:00-05:00
More information on Date.SpecifyKind can be found here: http://msdn.microsoft.com/en-us/library/bb546101.aspx