I used to encounter an error with DotNetNuke version 7 several time which displays all modules with a name of "undefined" and a broken picture.
This happens when people try to configure their DNN Web Api library to JSON format. Because in C# this is usually done by PascalCase and in JavaScript this is but done using camelCase. So when people want to consume the service with some javascript library, AngularJS for example, they configure the data source to JSON format. In DNN, it's usually done like this.
public class RouteMapper : IServiceRouteMapper { public void RegisterRoutes(IMapRoute mapRouteManager) { var formatter = System.Web.Http.GlobalConfiguration.Configuration.Formatters.JsonFormatter; formatter.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); mapRouteManager.MapHttpRoute("Invoice", "default", "{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional }, namespaces: new[] { "DnnWebApi.Controllers" }); } }
This will however configure the data format to be camelcase globally. And DNN has its own Web Api implementations which use actually PascalCase. So camelCase will make its client scripts break.
for (var i = 0; i < moduleList.length; i++) { ul.append('<li><div class="ControlBar_ModuleDiv" data-module=' + moduleList[i].ModuleID + '><div class="ModuleLocator_Menu"></div><img src="' + moduleList[i].ModuleImage + '" alt="" /><span>' + moduleList[i].ModuleName + '</span></div></li>'); }
So my solution is pretty simple and dumb. Switch to camelcase when the controller instantiates, and switch it back when it disposes.
public class AppController: DnnApiController, IDisposable { private IContractResolver _resolver; public AppController() { var formatter = System.Web.Http.GlobalConfiguration.Configuration.Formatters.JsonFormatter; _resolver = formatter.SerializerSettings.ContractResolver; formatter.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); } //your implementation... void IDisposable.Dispose() { var formatter = System.Web.Http.GlobalConfiguration.Configuration.Formatters.JsonFormatter; formatter.SerializerSettings.ContractResolver = _resolver; } }
没有评论:
发表评论