C# 在 ASP MVC 4 (Beta) 中将 DateTime 发布到 ApiController
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9417097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Posting DateTime to a ApiController in ASP MVC 4 (Beta)
提问by Bjarki Heiear
When I post a json object with a date property to a ApiController it won't deserialize into a date.
当我将具有日期属性的 json 对象发布到 ApiController 时,它不会反序列化为日期。
Server site code:
服务器站点代码:
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; }
}
Then I do a POST request with fiddler
然后我用 fiddler 做一个 POST 请求
POST http://localhost:62990/MegaTestHTTP/1.1
User-Agent: Fiddler
Host: localhost:62990
Content-Type: text/json
Content-Length: 54
{ "Date":"/Date(1239018869048)/", "Name":"Dude" }
POST http://localhost:62990/MegaTestHTTP/1.1
用户代理:提琴手
主机:本地主机:62990
内容类型:文本/json
内容长度:54
{ "日期":"/日期(1239018869048)/", "姓名":"Dude" }
But the object coming in only has the Nameproperty set, the Dateproperty is {01.01.0001 00:00:00}
但是进来的对象只有Name属性集,Date属性是{01.01.0001 00:00:00}
Am I missing any headers or project settings?
我是否缺少任何标题或项目设置?
Edit: The requests are actually coming from a HttpClient. Is it possible to format the date before sending the request over with HttpClient?
编辑:请求实际上来自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);
Edit: This is a known bug with the ASP MVC 4 Beta and the final version of ASP MVC 4 will use Json.netas a json serializer until then you can use the default XML serializer or switch out the default Json serializer for Json.net. More info can be found on hanselman blog
编辑:这是 ASP MVC 4 Beta 的一个已知错误,ASP MVC 4 的最终版本将使用Json.net作为 json 序列化程序,直到那时您可以使用默认的 XML 序列化程序或为Json.net切换出默认的 Json 序列化程序. 更多信息可以在hanselman 博客上找到
采纳答案by Bjarki Heiear
This is a known bug with the ASP MVC 4 Beta and the final version of ASP MVC 4 will use Json.netas a json serializer until then you can use the default XML serializer or switch out the default Json serializer for Json.net. More info can be found on hanselman blog
这是 ASP MVC 4 Beta 的一个已知错误,ASP MVC 4 的最终版本将使用Json.net作为 json 序列化程序,直到那时您可以使用默认的 XML 序列化程序或为Json.net切换出默认的 Json 序列化程序。更多信息可以在hanselman 博客上找到
Here is a small example of using the default XML Serializer to send DateTimewith HttpClient:
这是使用默认 XML SerializerDateTime与 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);
But if you would like to use json then here is a good blog post on using JSON.NET with ASP.NET Web API
但是如果你想使用 json 那么这里是一篇关于使用 JSON.NET 和 ASP.NET Web API的好博客文章
回答by Dmitry Nogin
Try to post your date/time as "yyyy-MM-dd HH:mm:ss". ASP MVC will handle it properly.
尝试将您的日期/时间发布为“yyyy-MM-dd HH:mm:ss”。ASP MVC 将正确处理它。
回答by Dave Ward
It appears that Web API doesn't accept dates in the old ASP.NET AJAX format for URL encoded POST data. There seems to be two formats that it accepts URL encoded dates in currently:
对于 URL 编码的 POST 数据,Web API 似乎不接受旧 ASP.NET AJAX 格式的日期。目前似乎有两种格式接受 URL 编码的日期:
ShortDateString: "2/23/2012"
短日期字符串:“2/23/2012”
ISO: "2012-02-23T00:00:00"
ISO:“2012-02-23T00:00:00”
The later is the ISO DateTime format, and there are a variety of code snippets you can find to help with converting a JavaScript Date object to that format. Several mentioned here: How do I output an ISO 8601 formatted string in JavaScript?
后者是 ISO DateTime 格式,您可以找到各种代码片段来帮助将 JavaScript 日期对象转换为该格式。这里提到了几个:如何在 JavaScript 中输出 ISO 8601 格式的字符串?
Web API doesstill accept the /Date()/ format if you send that data as JSON and set the Content-Type correctly though:
网页API确实仍然接受/日期()/格式,如果您发送的数据作为JSON和正确虽然设置的Content-Type:
$.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" }'
});
回答by James Webster
ASP.Net Web API uses the DataContractJsonSerializerwhich has bugs surrounding serialization of DateTime. You should use JSON.Net instead, and implement a MediaTypeFormatterthat uses JSON.Net instead of DataContractJsonSerializer. Check out my answer for a similar question here.
ASP.Net Web API 使用了DataContractJsonSerializer围绕DateTime. 您应该改用 JSON.Net,并实现MediaTypeFormatter使用 JSON.Net 而不是 DataContractJsonSerializer 的 。在此处查看我对类似问题的回答。

