【问题标题】:.Net WebApi 1 datetime converter.Net WebApi 1 日期时间转换器
【发布时间】:2015-04-13 17:14:32
【问题描述】:

我在 mvc 4.0 中有一个 webapi 1.0。

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

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

这是 curl 请求

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; }
}

【问题讨论】:

  • 您是否尝试过将服务器文化更改为不同于 en-US 的内容?
  • 是的,我已经有

标签: c# asp.net-mvc-4 asp.net-web-api


【解决方案1】:

在 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") );
    }
}

然后将此转换器添加到序列化设置中:

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new MyDateTimeConvertor());

【讨论】:

  • 是的,我知道,但就我而言,我不使用 json。传入请求采用 form-urlencoded 格式。像这样 ExpiryDate=30%2F04%2F2015&UserId=32
猜你喜欢
  • 1970-01-01
  • 2012-08-31
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 2013-02-09
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多