WebApi日期时间类型不一致POST与GET

WebApi日期时间类型不一致POST与GET

本文介绍了.NET WebApi日期时间类型不一致POST与GET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过GET请求从AngularJS到WebApi控制器进行JSON调用时,我的日期以本地"类型传递到我的模型中.很好,我希望它如何工作.

When I make a JSON call from AngularJS to my WebApi controller via a GET request, my dates come through to my model as 'Local' kind. This is fine and how I want it to work.

但是,当我将方法更改为POST时(在WebApi控制器和AngularJS客户端代码上),由于DateTime类型现在为UTC,所以日期已过了一个小时.日期在发送之前通过.toJSON()进行序列化,并且在查看GET和POST请求时,通过Chrome的网络检查,一切看起来都一样.

However, when I change the method to POST (on both the WebApi controller and my AngularJS client side code), the dates are an hour out because the DateTime kind is now UTC. The dates are serialized via .toJSON() before being sent and everything looks the same via Chrome's network inspection when looking at the GET and POST requests.

如何在POST和GET请求中保持DateTime Kind的一致性,使它们始终处于本地状态?

How can I keep the DateTime Kind's consistent across POST and GET requests so that they are always Local?

编辑#1:

Angular JS调用:

            var params = {
                DateFrom: detail.from.toJSON(),
                DateTo: detail.to.toJSON(),
                Filters: detail.filters
            };

            return http.post(window.urls.apiGetAllErrorsGraphData, params);

在我当前的示例中,params.DateFrom ="2014-04-30T23:00:00.000Z"的值,detail.from = 01/05/2014作为JS Date对象.

In my current example, the value of params.DateFrom = "2014-04-30T23:00:00.000Z", detail.from = 01/05/2014 as a JS Date object.

在这种情况下,"http.post"是我编写的Angular服务,基本上包装了HTTP调用.

'http.post' in this case is an Angular service that I wrote that basically wraps HTTP calls.

.NET WebAPI控制器

    [POST("api/errors/chart")]
    [HttpPost]
    [HttpOptions]
    public IHttpActionResult GetAllErrorsGraphData([FromBody]AllErrorChartDetails details)
    {
        var results = chartDataService.GenerateAllErrorsData(details.DateFrom, details.DateTo, details.Filters);

        return Ok(results.Select(x => new { date = x.Key, errors = x.Value }));
    }

如果您想知道方法中的属性是什么,我正在使用AttributeRouting.

I'm using AttributeRouting if you're curious what the attributes are over the method.

推荐答案

在检索DateTime对象时,是否可以将其转换为所需的格式?

Can you not just convert the DateTime object when you retrieve it to whatever format you need?

DateTime json = yourJsonMethod();
json = json.ToLocalTime();

这篇关于.NET WebApi日期时间类型不一致POST与GET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 09:58