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! Here is the whole response-error msg :
问题是它根本不会将它识别为JSON,但是,唉!这是整个响应错误消息:
{"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)"}}}
3 个解决方案
#1
2
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/
#2
0
I've gotten in the habit of returning an HttpResponseMessage so that I have direct control over the status and content type. Here's some code that will do that for you.
我已经养成了返回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;
}
#3
0
Just use List:
只需使用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. And change your service from IEnumerable to List:
编辑:更改为addRange方法。并将您的服务从IEnumerable更改为List:
public List<Category> GetCategories()
#1
2
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/
#2
0
I've gotten in the habit of returning an HttpResponseMessage so that I have direct control over the status and content type. Here's some code that will do that for you.
我已经养成了返回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;
}
#3
0
Just use List:
只需使用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. And change your service from IEnumerable to List:
编辑:更改为addRange方法。并将您的服务从IEnumerable更改为List:
public List<Category> GetCategories()