Return JsonNet type JSON from WebAPI in Orchard

旧巷老猫 提交于 2019-12-13 05:58:02

问题


In standard MVC I use JsonNet to return JSON that is in camelCase and sucessfully serializes entities that have related entities (which otherwise reports a "cycles" error" using the default serializer).

I'd like to do the same for a WebAPI controller in an Orchard module. By default it returns PascalCase JSON and reports a "cyles" exception when given a list of entities.

Can anyone explain how best to configure the JSON output from within the Orchard module, to mimic what JsonNet would produce?


回答1:


I've found a workaround, which is to set the JSON formatters settings to camelCase in an ActionFilter:

    public class CamelCaseJsonAttribute : ActionFilterAttribute {

    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        var jsonFormatter = actionContext.ControllerContext.Configuration.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }
}

But this seems inefficient, as it gets set on each request, rather than globally, once.

I'm guessing there is an extensibility point somewhere in a module to set the HttpConfiguration - can anyone tell me one way or the other?

Many thanks.



来源:https://stackoverflow.com/questions/17447058/return-jsonnet-type-json-from-webapi-in-orchard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!