您的位置:首页 > 其它

解决MVC 时间序列化的方法

2015-06-12 16:51 351 查看
1.全局处理

处理代码

publict static void SetSerializationJsonFormat(HttpConfiguration config)
{
// Web API configuration and services
var json = config.Formatters.JsonFormatter;
////(时间格式只支持2种)json.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
////时间格式("自定义格式")
json.SerializerSettings.Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
////移除json序列化器
////config.Formatters.Remove(config.Formatters.JsonFormatter);
}


在Application_Start调用SetSerializationJsonFormat(GlobalConfiguration.Configuration)全局设置

2.重写ActionResult

public class JsonResult : ActionResult
{
public JsonResult()
{
this.ContentEncoding = Encoding.UTF8;
this.ContentType = "application/json";
}

public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}

HttpResponseBase response = context.HttpContext.Response;
if (!string.IsNullOrEmpty(this.ContentType))
{
response.ContentType = this.ContentType;
}
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Data != null)
{
response.Write(NewtonsoftSerialize(this.Data));
response.End();
}
}

public Encoding ContentEncoding { get; set; }

public string ContentType { get; set; }

public object Data { get; set; }

private static string NewtonsoftSerialize(object value)
{
try
{
IsoDateTimeConverter timeFormat = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
return JsonConvert.SerializeObject(value, timeFormat);
}
catch
{
return string.Empty;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: