我有一个接收包含日期属性的对象的网络方法。我将代表对象的 json 传递给 webmethod。asp.net 自动将 json 字符串转换为对象,因此我的方法如下所示:
[WebMethod]
public static Object Save(MyObject item)
{
....
}
public class MyObject
{
DateTime date;
.....
}
当日期以美国格式发送时,这一切都很好:'MM/dd/yyyy'
当日期以欧洲格式发送时:'dd/MM/yyy'
我收到一个错误。
我在全球 asax 中设置线程的文化:
void Application_AcquireRequestState(object sender, EventArgs e)
{
var s = GetSessionValues();
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(s.CultureID);
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(s.CultureID);
}
此代码运行正确,它从会话中读取文化 ID 并设置它。从数据库登录时,文化 ID 被读入会话。
但这似乎对我收到错误的 web 方法预期的日期格式没有影响:
"31/08/2012 is not a valid value for DateTime.",
"StackTrace":"
at System.ComponentModel.DateTimeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)\r\n
at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n
at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n
at System.Web.Script.Serialization.ObjectConverter.AssignToPropertyOrField(Object propertyValue, Object o, String memberName, JavaScriptSerializer serializer, Boolean throwOnError)\r\n
at System.Web.Script.Serialization.ObjectConverter.ConvertDictionaryToObject(IDictionary`2 dictionary, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n
at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n
at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n
at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToType(Object o, Type type, JavaScriptSerializer serializer)\r\n
at System.Web.Script.Services.WebServiceMethodData.StrongTypeParameters(IDictionary`2 rawParams)\r\n
at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)\r\n
at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n
at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.FormatException"}
如何为 webmethod 设置预期的日期格式(我有很多这样的 web 方法,所以很明显我想要一个适用于所有这些方法的解决方案)。
谢谢