Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 为什么同一API中的不同端点返回不同的日期格式?_Asp.net_Json_Asp.net Mvc - Fatal编程技术网

Asp.net 为什么同一API中的不同端点返回不同的日期格式?

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

我有两个不同的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()));
}
其中,响应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;
有关更多信息,请查看