WebAPI, PascalCase and camelCase

In the RAW stack the ASP.NET WebAPI plays a big part in exposing data to the client and accepting data back in. This does mean that it is also the boundary of the AngularJS, or JavaScript, and C# world. And both of these worlds have their own, not always compatible standards. In this case I am referring to the normal way of naming properties on objects. In C# this is normally done using PascalCase and in JavaScript this is normally done using camelCase.

 

Bridging the gap

It turns out that being able to use the normal conventions on each side of the HTTP request is quite easy. When a request for a JSON formatted resource is made the WebAPI uses the popular JSON.NET serializer. By default JSON.NET creates JSON objects with the same casing as the corresponding C# objects which is the behavior we are seeing now. However it does ship with a CamelCasePropertyNamesContractResolver which does exactly what we want. So a simple change there is all that is needed.

   1: public static class WebApiConfig


   2: {


   3:     public static void Register(HttpConfiguration config)


   4:     {


   5:         // Web API configuration and services


   6:         config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =


   7:             new CamelCasePropertyNamesContractResolver();


   8:  


   9:         // Web API routes


  10:         config.MapHttpAttributeRoutes();


  11:  


  12:         config.Routes.MapHttpRoute("DefaultApi",


  13:             "api/{controller}/{id}",


  14:             new {id = RouteParameter.Optional});


  15:     }


  16: }




Add a few small changes to the AngularJS data bindings and the related code and we are all set.



 



Try it



The running application can be found here and the source on GitHub here.



 



Conclusion



The ASP.NET WebAPI makes it really easy to follow standard casing conventions both for C# and JavaScript and still have everything work as expected. Just the way I like it :-)



 



Index of posts on the RAW stack



See here for more posts on the RAW stack.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>