【问题标题】:Why are different endpoints in the same API returning different date formats?为什么同一 API 中的不同端点返回不同的日期格式?
【发布时间】:2016-09-29 09:05:39
【问题描述】:

我有两个不同的 API 端点。两个控制器都继承ApiController。两者都返回一个对象,每个对象都有一个 DateTime 类型的字段。

API 1:

[Route("OtherThings/{otherThingId:guid}/FirstThing", Name = "GetFirstThing")]
[HttpGet]
[ResponseType(typeof(Response1))]
public IHttpActionResult GetFirstThing(Guid otherThingId, [FromUri] DateTime? modifiedDate = null)
{
    var things = GetThings(otherThingId, modifiedDate);
    if (!things.Any())
    {
        return NotFound();
    }

    return Ok(new Response1(things.First()));
}

其中 Response1 定义为:

public class ReadingProgressResponse
{
    public DateTime DateTime { get; set; }
    // and other properties
}

示例响应:

{
    "dateTime": "2016-09-28T14:30:26"
}

API 2

[HttpGet]
[Route("{someId:guid}", Name = "SomeName")]
[ResponseType(typeof (Response2))]
public IHttpActionResult GetResponse2(Guid someId)
{
    var data = GetSomeData(someId);

    return Ok(new Response2(data));
}

其中Response2 定义为:

public class ScreenSessionResponse
{
    public DateTime ExpirationTime { get; set; }
    // and other fields
}

示例响应:

{
    "expirationTime": "2016-09-28T14:48:09Z"
}

请注意,API 1 在日期末尾没有“Z”,但 API 2 有。

为什么?我可以控制响应的格式吗?

【问题讨论】:

    标签: asp.net json asp.net-mvc


    【解决方案1】:

    是的,您可以控制日期的格式。

    在 global.asax 的 OnStart 方法中尝试此代码:

    // Convert all dates to UTC
    var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
    json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
    

    欲了解更多信息,请查看here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多