栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何从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)};}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/406836.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号