[英]WebAPI2 + Angular http GET - returning IEnumerable<Categories>. failed to serialize the response body for content type 'application/json
I'm learning this as we speak and find some of this pretty strange and hard ;) 我在学习时正在学习这个,发现其中一些非常奇怪和困难;)
Here is the rest service call in Angular: 这是Angular中的其余服务调用:
$scope.categories = [];
$scope.selectedCategory = null;
$http({
method: 'GET',
url: './api/file/GetCategories',
accept: 'application/json'
})
.success(function(result) {
$scope.categories = result;
});
Here is the service I'm trying to fetch : (C# - FileController.cs) 这是我要获取的服务:(C#-FileController.cs)
public IEnumerable<Category> GetCategories()
{
return FileServices.GetCategoriesForUser();
}
Fileservices method : 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;
}
The issue is that it probably don't recognize it as JSON at all, but, alas! 问题在于它可能根本不会将其识别为JSON,但是,a! Here is the whole response-error msg :
这是整个响应错误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)"}}}
Try adding this to the Register()
function in the config file in your App_Start folder: 尝试将其添加到App_Start文件夹的配置文件中的
Register()
函数中:
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
I had a similar problem and this fixed it for me. 我有一个类似的问题,这为我解决了。 This was taken from: http://social.msdn.microsoft.com/Forums/vstudio/en-US/a5adf07b-e622-4a12-872d-40c753417645/
摘自: http : //social.msdn.microsoft.com/Forums/vstudio/en-US/a5adf07b-e622-4a12-872d-40c753417645/
I've gotten in the habit of returning an HttpResponseMessage so that I have direct control over the status and content type. 我习惯于返回HttpResponseMessage,以便可以直接控制状态和内容类型。 Here's some code that will do that for you.
这里有一些代码将为您做到这一点。
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;
}
Just use List: 只需使用列表:
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 is an interface, you can't create instance of interface. IEnumerable是一个接口,您不能创建该接口的实例。
Edit: Changed to addRange method. 编辑:更改为addRange方法。 And change your service from IEnumerable to List:
并将您的服务从IEnumerable更改为List:
public List<Category> GetCategories()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.