Trevor Daniel Trevor Daniel - 1 month ago 15
C# Question

Self Hosted WebAPI Controller Dates in US not UK format

I have read numerous threads about this problem but have not been able to get it fixed.

I have a self-hosted API and based in the UK... So want UK datetime format

Basically, I am sending dates as DD/MM/YYYY as a GET to my APIController and they are coming into the controller as MM/DD/YYYY.

So, when I send 31/12/2016 I get a 400 error returned. When I send 12/31/2016 it works perfectly.

Here is my service where I am trying to set the culture to en-GB but it makes no difference to my problem.

public APICoreService()
{
InitializeComponent();

_config = new MyHttpsSelfHostConfiguration(ServiceAddress);
_config.MapHttpAttributeRoutes();
_config.Routes.MapHttpRoute("DefaultApi", "{controller}/{id}", new { id = RouteParameter.Optional });

// upload size control
_config.MaxReceivedMessageSize = 5242880; // 5mb
_config.MaxBufferSize = 5242880; // 5mb

// add the controller validation filter
_config.Filters.Add(new InventryCoreAPIService.Filters.ValidateViewModelAttribute());

// turn on error messages
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

_config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

// set the culture to solve the date problem
_config.Formatters.JsonFormatter.SerializerSettings.Culture = new CultureInfo("en-GB");
}


Can anyone give me any pointers please?

Answer

You should not be binding your date serializer to a specific date format or culture. Date format should be for presentation purposes only.

JSON is a data format, not a presentation format. JSON does not specify a date format but JavaScript does - in order to be compliant, it's generally a good idea to use the JavaScript format of date.

SO: The “right” JSON date format