如果将许多对象发送到我的 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);
}
}