我在Breeze中使用ASP.NET WebAPI 2。我希望能够在使用SaveChanges()方法保存更改时返回有意义的错误消息。这是在出现错误的情况下。 当前实现返回SaveResult。如何返回消息,例如
var cardDetail = _membershipContextProvider.Context.Database.SqlQuery<CardDetail>("IssuedCardsGetVerificationDetails @CardNo", parameter).FirstOrDefault();
if (cardDetail == null)
{
HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("The beneficiary with Card No. {0} was found in the NHIF database", CardNo)),
ReasonPhrase =string.Format("Card No. {0} Not Found in the NHIF Database!",CardNo)
};
throw new HttpResponseException(msg);
}
return cardDetail;
答案 0 :(得分:2)
您需要在自定义保存方法中抛出 EntityErrorsException 。此异常允许您为每个失败的实体指定顶级消息以及自定义消息。
[HttpPost]
public SaveResult MyCustomSaveMethod(JObject saveBundle) {
ContextProvider.BeforeSaveEntitiesDelegate = SaveThatMightThrow;
return ContextProvider.SaveChanges(saveBundle);
}
private Dictionary<Type, List<EntityInfo>> SaveThatMightThrow(Dictionary<Type, List<EntityInfo>> saveMap) {
List<EntityInfo> orderInfos;
// if this save tries to save ANY orders throw an exception.
if (saveMap.TryGetValue(typeof(Order), out orderInfos)) {
var errors = orderInfos.Select(oi => {
return new EFEntityError(oi, "WrongMethod", "Entity level detail error - Cannot save orders with this save method", "OrderID");
});
var ex = new EntityErrorsException("Top level error - Orders should not be saved with this method", errors);
// if you want to see a different error status code use this.
// ex.StatusCode = HttpStatusCode.Conflict; // Conflict = 409 ; default is Forbidden (403).
throw ex;
}
return saveMap;
}
请注意,Breeze 1.4.16中存在一个错误,其中顶级错误未正确传播(它以空字符串形式返回到客户端),但是实体级错误消息将会很好。这个错误已在最新的GitHub存储库中修复,但您需要从breeze.js和breeze.server.net存储库中获取固定代码,因为修复程序既适用于breeze.js客户端,也适用于ContextProvider breeze.server.net中的类。或者您可以在大约一周内等待下一次微风释放。