Why is the current thread's CultureInfo not being used when parsing a DateTime parameter on a 'WebMethod' call in ASP .NET?
I have an ASP .NET Web Forms application that makes use of the 'WebMethod' attribute for making AJAX calls from jQuery. I'm dealing with trying to localize the application so I recently created a web method that looks something like this for testing purposes:
[WebMethod]
public static string HandleDate(DateTime dateValue)
{
return dateValue.ToString("f");
}
The point of this method is to verify that if I set the CultureInfo properly the web method will parse the provided date correctly using the date formatting rules for that culture. Unfortunately, this code is never being reached. Instead, I'm seeing an error getting raised by the helper classes that allow these WebMethods to be called.
I have an HttpModule that is setting the 'CurrentCulture' and 'CurrentUICulture' properties of the current thread to 'pt-BR' (Brazilian Portuguese) at the 'BeginRequest' event.
Client side, I have a jQuery AJAX call to this 'HandleDate' web method that is providing the dateValue parameter as '18/10/2010'. In the 'pt-BR' culture this should evaluate to October 18, 2010 (day/month/year date format).
When I execute this I'm getting back an error indicating that the 'System.Web.Script.Serialization.ObjectConverter' is blowing up开发者_JS百科 stating that '18/11/2010' is not a valid value for DateTime. The stack trace included with the error indicates that this was thrown by the 'System.ComponentModel.DateTimeCoverter.ConvertFrom' method, which accepts the object to be converted in addition to a CultureInfo object representing the culture that should be applied during the conversion.
I fired up Reflector and it appears that the 'ObjectConverter' is invoking the 'DateTimeConverter' using CultureInfo.InvariantCulture instance, which I think is the problem.
How can I force this logic to use the CultureInfo attached to the current thread instead of the InvariantCulture?
I would recommend you change the parameter type to string
and then do the parsing yourself using DateTime.Parse
or TryParse
.
精彩评论