我正在使用Microsoft MVC 4 ApiController为Ember应用程序渲染JSON。API 控制器返回 JSON,如下所示:
[{"id": 1, "customerName": "Customer 1"}]
Ember 希望 JSON 使用对象根进行格式化,如下所示:
{"customers": [{"id": 1, "customerName": "Customer 1"}]
发布新的客户记录也是如此。Ember发布了JSON,它有对象根,而MVC希望JSON没有对象根:
{"customers": [{"customerName": "Customer 1"}]
我已经更改了WebApiConfig以将JSON属性更改为驼峰(因此键看起来像"客户名称"而不是"客户名称"(。我相信可以添加一个 JsonConverter 来添加/删除 JSON 对象根,但我不知道该怎么做。
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
控制器如下所示:
public class CustomersController : ApiController
{
private DatabaseContext db = new DatabaseContext();
public IEnumerable<Customer> GetCustomers()
{
return db.Customers.AsEnumerable();
}
public HttpResponseMessage PostCustomer([FromBody] Customer customer)
{
if (ModelState.IsValid)
{
db.Customers.Add(customer);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, customer);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = customer.Id }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
}
您可能会做这样的事情,将对象包装在具有 customers 属性的父对象中,尽管我还没有测试过它:
var mycust = new { customers = customer };
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, mycust);
或者,您可以使用自定义格式化程序,如以下要点所示:
https://gist.github.com/eed3si9n/4554127