我想将响应数据格式更改为
{
"$id": "1",
"$values": [
{
"$id": "2",
"OrderID": 3,
"Article": null
},
{
"$id": "3",
"OrderID": 4,
"Article": null
}
]
}
到
[
{
"OrderID": 3,
"Article": null
},
{
"OrderID": 4,
"Article": null
}
]
我尝试在WebApiConfig.cs文件中配置JsonFormatter,添加这两行
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
但不起作用。
这是控制器代码,它的类继承自ApiController
public List<OrderDto> Get()
{
var serviceResult = orderService.LoadOrders();
if (serviceResult.IsValid)
{
var orders = serviceResult.GetObject();
var ordersDto = Mapper.Map<List<Order>, List<OrderDto>>(orders);
return ordersDto;
}
else
{
return null;
}
}
对这个解决方案有什么想法吗?
编辑1:
OrderDto.cs代码
public class OrderDto
{
public int OrderID { get; set; }
public string Article { get; set; }
}
答案 0 :(得分:6)
[HttpGet]
,[HttpPost]
等Dtos
个对象而不是ViewModel
个对象,因为它不是纯粹的MVC体系结构,许多客户端可以通过不同的方式使用您的API。Request.CreateResponse(HttpStatusCode.BadRequest, "error message")
,而不是null
,而在您的else语句中带有一些错误消息。这将是一个快速的解决方案,但是我会考虑在服务的实现中引发异常,并根据此正确的错误消息返回客户端。这应该有效:
[System.Web.Http.HttpGet]
public HttpResponseMessage GetAllOrders()
{
//var serviceResult = orderService.LoadOrders();
// var isValid = serviceResult.IsValid
var isValid = true;
if (isValid)
{
// I used hardcoded values here just to show how to return a proper result
// you can call your service instead and do the mapping/other stuff
var result = new List<OrderDto>()
{
new OrderDto(){
OrderID = 3,
Article = "blah1"
},
new OrderDto(){
OrderID = 4,
Article = "blah2"
}
};
return Request.CreateResponse(HttpStatusCode.OK, result);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest, "Error Message");
}
}
public class OrderDto
{
public int OrderID { get; set; }
public string Article { get; set; }
}
WebApiConfig.cs内容:
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 }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
结果
var isValid = true;
时
var isValid = false;
时