Return camelCased JSON from Web API

前端 未结 6 1097
攒了一身酷
攒了一身酷 2020-12-31 11:42

I\'m trying to return camel cased JSON from an ASP.Net Web API 2 controller. I created a new web application with just the ASP.Net MVC and Web API bits in it. I hijacked t

6条回答
  •  长发绾君心
    2020-12-31 12:13

    In Register method of WebApiConfig, add this

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

    Full Code of WebApiConfig:

        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // Web API configuration and services
    
                // Web API routes
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
    
                config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    
            }
        }
    


    Make sure you have installed latest version of Json.Net/Newtonsoft.Json Installed and your API Action Method returns data in following way:

        [HttpGet]
        public HttpResponseMessage List()
        {
            try
            {
                var result = /*write code to fetch your result*/;
                return Request.CreateResponse(HttpStatusCode.OK, result);
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }
    

提交回复
热议问题