[英].Net WebApi 1 datetime converter
i have a webapi 1.0 inside mvc 4.0. 我在mvc 4.0中有一个webapi 1.0。
There's a way to change (globally) the default converter for a datetime field for webapi request for content-type x-www-form-urlencoded? 有一种方法可以(全局)更改针对内容类型x-www-form-urlencoded的webapi请求的datetime字段的默认转换器?
The field that the client sent to the server is in this format dd/mm/yyyy but the server seems to convert only date in this format mm/dd/yyyy 客户端发送到服务器的字段的格式为dd / mm / yyyy,但是服务器似乎仅转换为mm / dd / yyyy格式的日期
This is the curl request 这是卷曲的要求
curl "http://xxxx/yyy/apimethod/"
-H "Accept-Encoding: gzip, deflate"
-H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8"
--data "ExpiryDate=30%2F04%2F2015&UserId=32"
This is the method 这是方法
[HttpPost]
public HttpResponseMessage apimethod(MyModel model) {}
and this is the model 这就是模型
public class MyModel{
public int UserId { get; set; }
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime ExpiryDate { get; set; }
}
In ASP.NET Web API, you can add different Json.NET DateTimeConverters through the JsonFormatter's SerializerSettings to make your Serializer use different DateTime format. 在ASP.NET Web API中,可以通过JsonFormatter的SerializerSettings添加不同的Json.NET DateTimeConverters,以使您的Serializer使用不同的DateTime格式。
public class MyDateTimeConvertor : DateTimeConverterBase
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return DateTime.ParseExact(reader.Value.ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue( ((DateTime)value).ToString("dd/MM/yyyy") );
}
}
And then add this converter to serialization settings: 然后将此转换器添加到序列化设置中:
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new MyDateTimeConvertor());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.