问题描述:

Assume we have a WCF service which takes some DateTime object and works with it and we have a client which sends it in format dd/mm/yyyy. But this service is also called from JS which should send exact DateTime, this is why it is using yyyy-MM-ddTHH:mm:ss.fffzzz format.

Is it possible to create a Culture which is taking two formats and do no write disgusting ifs like if (DateTime.TryParse(format1, out dt) || DateTime.TryParse(format2, out dt) || DateTime.TryParse(format3, out dt) || ...)

Another disadvantage of this code is that we also have to duplicate it for DateTimeOffset as well

网友答案:

This is how ASP.NET MVC handles the issue. I think the same principles apply to a service implemented using another technology such as WCF. These conventions are used by web services.

ASP.NET MVC (including Web API) performs a culture-insensitive parsing on parameters passed in the querystring. Therefore, dates in the URL have to be in the universal format yyyy-mm-dd. Form values (or any value in request body) are expected to be in the format specified by the server. This means that a server set to the UK culture will expect dates to be in the UK date format: dd-mm-yyyy.

Why is culture-insensitive parsing performed on items in the URL?

There is a very good, logical and convenient reason why culture-insensitive parsing is performed on items in the URL. Imagine I see an item on sale and the sale has from and to dates in the URL. If I email that link to my friend (I live in Canada) in Germany, I want them to see the same page. If a culture-sensitive parse was performed on the date in the URL, my friend may be presented a totally different sale or may be presented a page not found-that will not be good.

So to answer your question, the client calling your WCF service should provide the date to your service in the format specified by the service unless the date is in the URL in which case the client should provide it in the universal format yyyy-mm-dd.

Another option is for the client to provide the culture to the service, for example, in the SOAP header, and the service will use that culture when parsing.

相关阅读:
Top