如何从ASP.NET MVC控制器方法返回由JSON.NET序列化的camelCase JSON?

如何从ASP.NET MVC控制器方法返回由JSON.NET序列化的camelCase JSON?,第1张

如何从ASP.NET MVC控制器方法返回由JSON.NET序列化的camelCase JSON?

我在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)};}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5016487.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存