在 ASP MVC 4(测试版)中将日期时间发布到 ApiController

发布于 2025-01-08 02:36:49 字数 1858 浏览 1 评论 0 原文

当我将带有日期属性的 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; }
}

然后我用 fiddler 执行 POST 请求

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

用户代理:Fiddler

主机:本地主机:62990

内容类型:text/json

内容长度:54

{ "日期":"/日期(1239018869048)/", “姓名”:“伙计” }

传入的对象仅设置了 Name 属性,Date 属性为 {01.01.0001 00:00:00}

我是否缺少任何标头或项目设置?


编辑:请求实际上来自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);

编辑:这是 ASP MVC 4 Beta 的一个已知错误,ASP MVC 4 的最终版本将使用 Json.net 作为 json 序列化器,在此之前您可以使用默认的 XML 序列化器或切换 Json.net 的默认 Json 序列化器。更多信息请访问 hanselman 博客

When I post a json object with a date property to a ApiController it won't deserialize into a date.

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

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

User-Agent: Fiddler

Host: localhost:62990

Content-Type: text/json

Content-Length: 54

{
"Date":"/Date(1239018869048)/",
"Name":"Dude"
}

But the object coming in only has the Name property set, the Date property is {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?

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.net as 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

弄潮 2025-01-15 02:36:49

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

Try to post your date/time as "yyyy-MM-dd HH:mm:ss". ASP MVC will handle it properly.

や莫失莫忘 2025-01-15 02:36:49

看来 Web API 不接受旧 ASP.NET AJAX 格式的日期作为 URL 编码的 POST 数据。目前似乎有两种格式接受URL编码的日期:

ShortDateString: "2/23/2012"

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

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

如果您将数据作为 JSON 发送并正确设置 Content-Type,Web API 确实仍然接受 /Date()/ 格式:

$.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" }'
});

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:

ShortDateString: "2/23/2012"

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?

Web API does still accept the /Date()/ format if you send that data as JSON and set the Content-Type correctly though:

$.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" }'
});
写下不归期 2025-01-15 02:36:49

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

,这是使用默认 XML 序列化器的一个小示例使用 HttpClient 发送 DateTime

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

但是如果您想使用 json,那么这里有一篇关于 使用JSON.NET 与 ASP.NET Web API

This is a known bug with the ASP MVC 4 Beta and the final version of ASP MVC 4 will use Json.net as 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

Here is a small example of using the default XML Serializer to send DateTime with 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

棒棒糖 2025-01-15 02:36:49

ASP.Net Web API 使用 DataContractJsonSerializer,它存在围绕 DateTime 序列化的错误。您应该改用 JSON.Net,并实现一个使用 JSON.Net 而不是 DataContractJsonSerializer 的 MediaTypeFormatter此处查看我对类似问题的回答。

ASP.Net Web API uses the DataContractJsonSerializer which has bugs surrounding serialization of DateTime. You should use JSON.Net instead, and implement a MediaTypeFormatter that uses JSON.Net instead of DataContractJsonSerializer. Check out my answer for a similar question here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文