.Net WebApi 1日期时间转换器 [英] .Net WebApi 1 datetime converter

查看:155
本文介绍了.Net WebApi 1日期时间转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mvc 4.0中有一个webapi 1.0.

i have a webapi 1.0 inside mvc 4.0.

有一种方法可以(全局)更改内容类型x-www-form-urlencoded的webapi请求的datetime字段的默认转换器?

There's a way to change (globally) the default converter for a datetime field for webapi request for content-type x-www-form-urlencoded?

客户端发送到服务器的字段的格式为dd/mm/yyyy,但是服务器似乎只转换了mm/dd/yyyy格式的日期

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

这是卷曲请求

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" 

这是方法

[HttpPost]
public HttpResponseMessage apimethod(MyModel 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; }
}

推荐答案

在ASP.NET Web API中,您可以通过JsonFormatter的SerializerSettings添加不同的Json.NET DateTimeConverters,以使您的Serializer使用不同的DateTime格式.

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.

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());

这篇关于.Net WebApi 1日期时间转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆