我正在尝试从ASP.Net Web API 2控制器返回驼峰式的JSON。我创建了一个只包含ASP.Net MVC和Web API部分的新Web应用程序。我像这样劫持了ValuesController:
public class ValuesController : ApiController
{
public class Thing
{
public int Id { get; set; }
public string FirstName { get; set; }
public string ISBN { get; set; }
public DateTime ReleaseDate { get; set; }
public string[] Tags { get; set; }
}
// GET api/values
public IHttpActionResult Get()
{
var thing = new Thing
{
Id = 123,
FirstName = "Brian",
ISBN = "ABC213",
ReleaseDate = DateTime.Now,
Tags = new string[] { "A", "B", "C", "D"}
};
return Json(thing);
}
}
在IE中运行此代码,我得到以下结果:
{"Id":123,"FirstName":"Brian","ISBN":"ABC213","ReleaseDate":"2014-10-20T16:26:33.6810554-04:00","Tags":["A","B","C","D"]}
在K. Scott Allen的帖子中,讨论了这个主题后,我将以下内容添加到WebApiConfig.cs文件的Register方法中:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
然而,我的结果仍然存在大写字母。我是否漏掉了什么?我已经尝试了其他几种方法,但仍未奏效。