hemtros
2/1/2017 - 2:54 PM

CamelCaseContractResolving : So that API from ASP.NET provides JSON with camelCasing

CamelCaseContractResolving :

So that API from ASP.NET provides JSON with camelCasing

//put this in Register method of WebApiConfig.cs. Using Newtonsoft.Json.Serialization

var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  //inherit controller with action methods from JsonController instead of plain Controller class
  public class JsonController: Controller
    {
        protected new ActionResult Json(object data, JsonRequestBehavior behaviour = JsonRequestBehavior.DenyGet)
        {
            var jsonSerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            if (Request.RequestType == WebRequestMethods.Http.Get && behaviour == JsonRequestBehavior.DenyGet)
            {
                throw new InvalidOperationException("GET is not permitted for this request");
            }

            var jsonResult = new ContentResult
            {
                Content = JsonConvert.SerializeObject(data, jsonSerializerSettings),
                ContentType = "application/json",
            };

            return jsonResult;
        }
    }