namespace ChatRoomServer.Www.Models { using System; using System.Web.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; /// /// 使用Json.Net进行序列化的结果 /// public class Json2Result : JsonResult { static JsonSerializerSettings _camelJsonSetting = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; /// /// 获得或设置经行回调的js函数名 /// public string CallbackJsFunction { get; set; } /// /// 获得是否使用缩进 /// public bool Indent { get; set; } /// /// 获得或设置是否使用Camel命名方式 /// public bool UseCamelName { get; set; } public override void ExecuteResult(ControllerContext context) { var request = context.HttpContext.Request; CallbackJsFunction = CallbackJsFunction.DefaultForEmpty(request.QueryString["callback"] ?? ""); var response = context.HttpContext.Response; response.ContentType = ContentType.DefaultForEmpty(CallbackJsFunction.IsNullOrEmpty() ? "application/json" : "text/javascript"); if (ContentEncoding != null) response.ContentEncoding = ContentEncoding; if (Data != null) { if (!CallbackJsFunction.IsNullOrEmpty()) { response.Write(CallbackJsFunction); response.Write("("); } response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(Data, Indent ? Formatting.Indented : Formatting.None, UseCamelName ? _camelJsonSetting : null)); if (!CallbackJsFunction.IsNullOrEmpty()) { response.Write(")"); } } } } }