[英]WebAPI OData Error The ObjectContent type failed to serialize the response body for content type 'application/json…'
[英]WebAPI2 + Angular http GET - returning IEnumerable<Categories>. failed to serialize the response body for content type 'application/json
我在學習時正在學習這個,發現其中一些非常奇怪和困難;)
這是Angular中的其余服務調用:
$scope.categories = [];
$scope.selectedCategory = null;
$http({
method: 'GET',
url: './api/file/GetCategories',
accept: 'application/json'
})
.success(function(result) {
$scope.categories = result;
});
這是我要獲取的服務:(C#-FileController.cs)
public IEnumerable<Category> GetCategories()
{
return FileServices.GetCategoriesForUser();
}
Fileservices方法:
public static IEnumerable<Category> GetCategoriesForUser()
{
User currentUser = UserServices.GetLoggedInUser();
IEnumerable<Category> userCategories;
using (var context = new PhotoEntities())
{
userCategories = context.Categories.Where(c => c.UserId == currentUser.Id);
}
return userCategories;
}
問題在於它可能根本不會將其識別為JSON,但是,a! 這是整個響應錯誤msg:
{"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Error getting value from 'Categories' on 'System.Data.Entity.DynamicProxies.User_523AFE24D26493BB74E43EAA23AAEBFD40D7EABFCAA3A6105EB951B365E60A04'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":" at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.","ExceptionType":"System.ObjectDisposedException","StackTrace":" at System.Data.Entity.Core.Objects.ObjectContext.get_Connection()\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.Load()\r\n at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()\r\n at System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)\r\n at System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__1(TProxy proxy, TItem item)\r\n at System.Data.Entity.DynamicProxies.User_523AFE24D26493BB74E43EAA23AAEBFD40D7EABFCAA3A6105EB951B365E60A04.get_Categories()\r\n at GetCategories(Object )\r\n at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"}}}
嘗試將其添加到App_Start文件夾的配置文件中的Register()
函數中:
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
我有一個類似的問題,這為我解決了。 摘自: http : //social.msdn.microsoft.com/Forums/vstudio/en-US/a5adf07b-e622-4a12-872d-40c753417645/
我習慣於返回HttpResponseMessage,以便可以直接控制狀態和內容類型。 這里有一些代碼將為您做到這一點。
public class StuffController : ApiController
{
public HttpResponseMessage Get()
{
List<SomeModel> models = ReadModels();
return GetJsonResponse(models);
}
}
public static HttpResponseMessage GetJsonResponse(object serializableObject)
{
string jsonText = JsonConvert.SerializeObject(serializableObject, Formatting.Indented);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(jsonText, Encoding.UTF8, "text/plain");
return response;
}
只需使用列表:
public static List<Category> GetCategoriesForUser()
{
User currentUser = UserServices.GetLoggedInUser();
IEnumerable<Category> userCategories = new List<Category>();
using (var context = new PhotoEntities())
{
userCategories.addRange(context.Categories.Where(c => c.UserId == currentUser.Id).toList());
}
return userCategories;
}
IEnumerable是一個接口,您不能創建該接口的實例。
編輯:更改為addRange方法。 並將您的服務從IEnumerable更改為List:
public List<Category> GetCategories()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.