我试图将一个IEnumerable从web api控制器发送到AngularJs控制器。 我正在使用的代码是
Web Api:
readonly InventoryEntities _db = new InventoryEntities();
public IEnumerable<FDVOEligibilityRequest> Get()
{
return _db.FDVOEligibilityRequests.AsEnumerable();
}
AngularJS:
//get all customer information
$http.get("/api/Customer/").success(function (data) {
$scope.requests = data;
$scope.loading = false;
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
这很好用,但现在我使用linq来包含相关的表,但它不起作用。 angularJs代码是相同的。 我做错了什么?
readonly InventoryEntities _db = new InventoryEntities();
public IEnumerable<FDVOEligibilityRequest> Get()
{
return _db.FDVOEligibilityRequests
.Include("FDVOEligibilityRequestMandatoryField")
.Include("FDVOEligibilityRequestDCCField").AsEnumerable();
}
我确实在控制器中获取了我想要的数据,但是当我尝试将其发送回角度时,我得到500(内部服务器错误)angular.js:10722
这就是FDVOEligibilityRequest在新的Web Api控制器中的样子
public partial class FDVOEligibilityRequest
{
public int Id { get; set; }
public string TestName { get; set; }
public string GroupName { get; set; }
public int MandatoryFieldsID { get; set; }
public int DCCFieldsID { get; set; }
public virtual FDVOEligibilityRequestMandatoryField FDVOEligibilityRequestMandatoryField { get; set; }
public virtual FDVOEligibilityRequestDCCField FDVOEligibilityRequestDCCField { get; set; }
}
答案 0 :(得分:0)
如果它是500并且在您成功从您的操作返回后发生,那么在序列化期间它可能是一个例外。
我建议检查FDVOEligibilityRequest和FDVOEligibilityRequestMandatoryField / FDVOEligibilityRequestDCCField之间没有循环引用。
或尝试使用here中的代码进行诊断:
string Serialize<T>(MediaTypeFormatter formatter, T value)
{
// Create a dummy HTTP Content.
Stream stream = new MemoryStream();
var content = new StreamContent(stream);
/// Serialize the object.
formatter.WriteToStreamAsync(typeof(T), value, stream, content, null).Wait();
// Read the serialized string.
stream.Position = 0;
return content.ReadAsStringAsync().Result;
}
try {
var val = _db.FDVOEligibilityRequests
.Include("FDVOEligibilityRequestMandatoryField")
.Include("FDVOEligibilityRequestDCCField").AsEnumerable();
var str = Serialize(new JsonMediaTypeFormatter(), val);
}
catch (Exception x)
{ // break point here
}
ps:在这种情况下,common suggestion是使用DTO而不是像Automapper这样的EF对象。