我在Mats Karlsson的博客中找到了解决此问题的绝佳方法。解决方案是编写ActionResult的子类,该子类通过JSON.NET序列化数据,并将后者配置为遵循camelCase约定:
public class JsonCamelCaseResult : ActionResult{ public JsonCamelCaseResult(object data, JsonRequestBehavior jsonRequestBehavior) { Data = data; JsonRequestBehavior = jsonRequestBehavior; } public Encoding ContentEncoding { get; set; } public string ContentType { get; set; } public object Data { get; set; } public JsonRequestBehavior JsonRequestBehavior { get; set; } public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."); } var response = context.HttpContext.Response; response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json"; if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data == null) return; var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; response.Write(JsonConvert.SerializeObject(Data, jsonSerializerSettings)); }}
然后在MVC控制器方法中按如下所示使用此类:
public ActionResult GetPerson(){ return new JsonCamelCaseResult(new Person { FirstName = "Joe", LastName = "Public" }, JsonRequestBehavior.AllowGet)};}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)