0

如果将许多对象发送到我的 Web api 控制器以插入到我的数据库中,那么最好的响应是什么,其中有些可能成功,有些可能失败?我认为一个正常的 HTTP 响应是不够的 - 找到某种方法来返回一个成功的 JSON 字符串会更好,什么没有?如果是这样,我该怎么做?

我的 Post 控制器如下所示。

谢谢你的帮助,

标记

    public HttpResponseMessage PostBooking(Booking[] bookings)
    {
        if (ModelState.IsValid)
        {
            foreach (var booking in bookings)
            {
                // check if there are any bookings already with this HID and RID...
                var checkbooking = db.Bookings.Where(h => h.HID == booking.HID && h.RID == booking.RID).ToList();
                // If so, return a response of conflict
                if (checkbooking.Count != 0 || checkbooking.Any())
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Conflict));
                }
                else
                {
                    // If not add the booking to the database and return a response of Created
                    db.Bookings.Add(booking);
                    db.SaveChanges();
                }
            } 
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
            return response;
        }
        else
        {
            // Model is not valid, so return BadRquest
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }
4

1 回答 1

1

您可以返回一个 JSON 列表,其中包含未能插入的对象的 id:

{
    "failedIds": [
        4,
        7,
        9
    ]
}

由于请求未成功完成,500 HTTP 响应状态代码似乎也很合适。

您甚至可以更进一步,并解释为什么每个特定 id 的插入失败:

{
    "failed": [
        {
            "id": 4,
            "reason": "database unavailable"
        },
        {
            "id": 7,
            "reason": "network cable unplugged"
        },
        {
            "id": 9,
            "reason": "a thief is currently running away with our server"
        }
    ]
}
于 2012-06-20T09:13:14.837 回答