从WebApi中的json对象列表中删除引用$ id

时间:2019-02-22 12:07:40

标签: c# json api json.net serializer

我想将响应数据格式更改为

{
    "$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; }
}

1 个答案:

答案 0 :(得分:6)

  1. 我相信,如果您使用的是Web API,则要澄清操作类型,应使用属性(例如, [HttpGet][HttpPost]
  2. 在使用API​​时,我会使用Dtos个对象而不是ViewModel个对象,因为它不是纯粹的MVC体系结构,许多客户端可以通过不同的方式使用您的API。
  3. 我希望返回BadRequest响应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;

enter image description here

var isValid = false;

enter image description here