ranjit0829
ranjit0829

Reputation: 21

How to fix this webapi routing configuration?

I have this code written in WebApiConfig.cs, where it does not behave as expected. eg: Camel-casing of json and excluding properties of null values.

I need guidance to locate any missing or incorrect code in the snippet below.

This is a web application with WebApiConfig.cs, where I am trying to configure Camel-casing of json and excluding properties of null values from the responses.

Currently the Response object does not have Camel-casing of json and includes properties with null values.

public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;

        jsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
        jsonFormatter.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
        jsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        config.Formatters.Add(jsonFormatter);
        config.Formatters.Remove(config.Formatters.XmlFormatter);

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

Thank you for help in advance.

Upvotes: 0

Views: 62

Answers (1)

Hasta Tamang
Hasta Tamang

Reputation: 2263

Use HttpConfiguration that was passed into your Register Method.

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    config.Formatters.Remove(config.Formatters.XmlFormatter); 
    var jsonFormatter = config.Formatters.JsonFormatter;

    jsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
    jsonFormatter.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
    jsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
    jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

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

Upvotes: 1

Related Questions