Tuesday 13 October 2015

Format WebAPI browser requests to Camel casing Json documents

If we send a GET request to WebAPI , by default it is returning a XML document. The reason is given in this post.
It is nice if we can format the browser output nicely with camel casing, proper intending etc. Then the client can discover the output easily. All we need to do it add the following formatting code to the WebApiConfig class.
 
 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
           
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();


            config.Formatters.JsonFormatter.SerializerSettings.Formatting
                = Newtonsoft.Json.Formatting.Indented;

            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver
                = new CamelCasePropertyNamesContractResolver();
        }
    }

The result is more user friendly output as follows.

No comments:

Post a Comment