将DateTime发布到ASP MVC 4(Beta)中的ApiController

Bja*_*ðar 12 c# asp.net-mvc httpclient asp.net-mvc-4 asp.net-web-api

当我将带有日期属性的json对象发布到ApiController时,它不会反序列化为日期.

服务器站点代码:

public class MegaTestController : ApiController
{
    // POST /megatest
    public void Post(ttt value)
    {
        string sdf = "!sad";
    }
}

public class ttt
{
    public DateTime Date { get; set; }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后我用fiddler做一个POST请求

POST http:// localhost:62990/MegaTest HTTP/1.1

用户代理:Fiddler

主持人:localhost:62990

内容类型:text/json

内容长度:54

{"日期":"/日期(1239018869048)/","名称":"Dude"}

但进入的对象只有Name属性集,Date属性为{01.01.0001 00:00:00}

我错过了任何标题或项目设置吗?


编辑:请求实际上来自a HttpClient.是否可以在发送请求之前格式化日期HttpClient

public Task<T> Create<T>(T item)
{
    var service = new HttpClient();
    service.BaseAddress = new Uri("http://localhost:62990");

    var method = typeof(T).Name + "s"; // in this case it will be ttts

    var req = new HttpRequestMessage<T>(item);
    req.Content.Headers.ContentType = new MediaTypeHeaderValue("text/json");

    return service.PostAsync(method, req.Content).ContinueWith((reslutTask) =>
    {
        return reslutTask.Result.Content.ReadAsAsync<T>();
    }).Unwrap();
}

var data = new ttt { Name = "Dude", Date = DateTime.Now };
Create(data);
Run Code Online (Sandbox Code Playgroud)

编辑:这是ASP MVC 4 Beta的已知错误,ASP MVC 4的最终版本将使用Json.net作为json序列化程序,直到那时您可以使用默认的XML序列化程序或为Json.net切换默认的Json序列化程序.更多信息可以在hanselman博客找到

Dmi*_*gin 17

尝试将您的日期/时间发布为"yyyy-MM-dd HH:mm:ss".ASP MVC将正确处理它.

  • 这不是取决于当前的服务器文化吗? (3认同)

Dav*_*ard 8

对于URL编码的POST数据,Web API似乎不接受旧的ASP.NET AJAX格式的日期.目前似乎有两种格式接受URL编码日期:

ShortDateString:"2/23/2012"

ISO:"2012-02-23T00:00:00"

后者是ISO DateTime格式,您可以找到各种代码片段来帮助将JavaScript Date对象转换为该格式.这里提到的几个:如何在JavaScript中输出ISO 8601格式的字符串?

网页API 确实仍然接受/日期()/格式,如果您发送的数据作为JSON和设置的内容类型,虽然正确:

$.ajax({
  url: 'MegaTest',
  type: 'POST',
  // Setting this Content-Type and sending the data as a JSON string
  //  is what makes the old /Date()/ format work.
  contentType: 'application/json',
  data: '{ "Date":"/Date(1239018869048)/", "Name":"Dude" }'
});
Run Code Online (Sandbox Code Playgroud)


Bja*_*ðar 4

这是 ASP MVC 4 Beta 的一个已知错误,ASP MVC 4 的最终版本将使用Json.net作为 json 序列化器,在此之前您可以使用默认的 XML 序列化器或为Json.net切换默认的 Json 序列化器。更多信息可以在汉塞尔曼博客上找到

下面是一个使用默认 XML 序列化器DateTime通过 HttpClient 发送的小示例:

var service = new HttpClient();
service.BaseAddress = url;

var mediaType = new MediaTypeHeaderValue("application/xml");
XmlMediaTypeFormatter formater = new XmlMediaTypeFormatter();
var req = new HttpRequestMessage<T>(item, mediaType, new MediaTypeFormatter[] { formater });

service.PutAsync(method, req.Content);
Run Code Online (Sandbox Code Playgroud)

但如果您想使用 json,那么这里有一篇关于将 JSON.NET 与 ASP.NET Web API 结合使用的好博客文章