Asp.net 为什么同一API中的不同端点返回不同的日期格式?
我有两个不同的API端点。两个控制器都继承ApiController。两者都返回一个对象,每个对象都有一个类型为Asp.net 为什么同一API中的不同端点返回不同的日期格式?,asp.net,json,asp.net-mvc,Asp.net,Json,Asp.net Mvc,我有两个不同的API端点。两个控制器都继承ApiController。两者都返回一个对象,每个对象都有一个类型为DateTime的字段 API 1: [Route("OtherThings/{otherThingId:guid}/FirstThing", Name = "GetFirstThing")] [HttpGet] [ResponseType(typeof(Response1))] public IHttpActionResult GetFirstThing(Guid otherThin
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()));
}
其中,响应1定义为:
public class ReadingProgressResponse
{
public DateTime DateTime { get; set; }
// and other properties
}
public class ScreenSessionResponse
{
public DateTime ExpirationTime { get; set; }
// and other fields
}
样本响应:
{
"dateTime": "2016-09-28T14:30:26"
}
{
"expirationTime": "2016-09-28T14:48:09Z"
}
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));
}
其中响应2
定义为:
public class ReadingProgressResponse
{
public DateTime DateTime { get; set; }
// and other properties
}
public class ScreenSessionResponse
{
public DateTime ExpirationTime { get; set; }
// and other fields
}
样本响应:
{
"dateTime": "2016-09-28T14:30:26"
}
{
"expirationTime": "2016-09-28T14:48:09Z"
}
请注意,API 1在日期末尾没有“Z”,但API 2有
为什么??我可以控制响应的格式吗?是的,您可以控制日期的格式 在global.asax的OnStart方法中尝试以下代码:
// Convert all dates to UTC
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
有关更多信息,请查看