我们需要一种机制,以便当特定的数据类型(比如日期时间)到达Web API时,我们应该能够拦截它和它。对该数据执行一些业务逻辑转换。
对于响应我们已经能够实现如下,但需要你的 有关如何拦截请求的帮助?
我尝试了什么? DateTimeConverter类:
public class DateTimeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime);
}
public override bool CanRead
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return true;
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var timeUtc = (DateTime)value;
TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime easternTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, easternZone);
writer.WriteValue(easternTime);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// the default deserialization works fine,
// but otherwise we'd handle that here
throw new NotImplementedException();
}
}
注册: -
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
jsonFormatter.SerializerSettings.Converters.Add(new TimeSpanConverter());
jsonFormatter.SerializerSettings.Converters.Add(new DateTimeConverter());
}