获取记录时发生Web api 2错误 [英] Web api 2 error occured while getting the record

查看:96
本文介绍了获取记录时发生Web api 2错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从数据库获取数据,我有产品控制器和两个实体相关(类别和供应商)到产品实体。



发生错误:

url:http:// localhost:43938 / api / products



错误:



i have tried to get the data from database, i have product controller and two entity are related(Category and supplier) to the product entity.

error occurred:
url: http://localhost:43938/api/products

Error:

{"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'text/html; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.Product_38D1FFB7107F8535EF889B819ADB900579A7E9B61EEF00299400B8FA6949CA63'. Path '[0].Category.Products'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":" at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference(JsonWriter writer, Object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract 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.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.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.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract 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 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.Web.Http.WebHost.HttpControllerHandler.d__1b.MoveNext()"}}





我的尝试:



web api方法:< br $>




What I have tried:

web api method:

[Route("api/Products", Name = "Products")]
       public IQueryable<Product> GetProducts()
       {
           return db.Products;
       }







实体框架创建类:






Entity framework created class:

public partial class Product
   {
       public int PId { get; set; }
       public string ProductName { get; set; }
       public Nullable<decimal> Price { get; set; }
       public Nullable<int> SId { get; set; }
       public Nullable<int> CId { get; set; }

       public virtual Category Category { get; set; }
       public virtual Supplier Supplier { get; set; }
   }







WebApiConfig.cs




WebApiConfig.cs

config.Formatters.JsonFormatter.SupportedMediaTypes
  .Add(new MediaTypeHeaderValue("text/html"));
      }

推荐答案

首先,你为什么要提出请求并在网络上期待tex / html api将返回json?



因此,抛开格式差异,一些问题在于您通过Web API直接从数据库返回实体。您的产品类可能与您应用中的其他类/表具有复杂的关系。例如:产品与订单或类似产品挂钩。



你有几个选择:



1)而不是返回一个实体,返回一个你完全控制的模型类

2)改变你的web api global.asx添加



So first thing, why are you making the request and expecting tex/html when web api will return json?

So putting aside the formatting discrepancy, some of the issues lie with you returning entities directly from your DB via Web API. Your products class probably has a complex relationship to some other class/table in your app. Ex: Products are tied to Orders or something like that.

You have a few options:

1) Instead of returning an entity, return a model class that you have full control over
2) Alter your web api global.asx to add

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
            GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);





关于此的说明,你正在删除XML格式化程序。对你来说无关紧要,但要记住这一点。



3)或者在Web API操作本身中添加以下代码片段。没有尝试过这个,但快速谷歌搜索你的问题返回了大量的结果,其中包含了这个建议。





A note on this, you are removing the XML formatter. May not matter for you but keep this in mind.

3) Or Add the following code snippet locally within the Web API action itself. Haven't tried this one but quick google search for your problem returns tons of results of which this suggestion was included.

context.Configuration.ProxyCreationEnabled = false;


这篇关于获取记录时发生Web api 2错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆