[英]Self referencing loop detected - Getting back data from WebApi to the browser
我正在使用实体框架并且在将父子数据获取到浏览器时遇到问题。 这是我的课程:
public class Question
{
public int QuestionId { get; set; }
public string Title { get; set; }
public virtual ICollection<Answer> Answers { get; set; }
}
public class Answer
{
public int AnswerId { get; set; }
public string Text { get; set; }
public int QuestionId { get; set; }
public virtual Question Question { get; set; }
}
我正在使用以下代码返回问答数据:
public IList<Question> GetQuestions(int subTopicId, int questionStatusId)
{
var questions = _questionsRepository.GetAll()
.Where(a => a.SubTopicId == subTopicId &&
(questionStatusId == 99 ||
a.QuestionStatusId == questionStatusId))
.Include(a => a.Answers)
.ToList();
return questions;
}
在 C# 方面,这似乎有效,但是我注意到答案对象引用了问题。 当我使用 WebAPI 将数据发送到浏览器时,我收到以下消息:
“ObjectContent`1”类型无法序列化内容类型“application/json”的响应主体; 字符集=utf-8'。
检测到类型为“Models.Core.Question”的属性“question”的自引用循环。
这是因为问题有答案并且答案有对问题的引用吗? 我看过的所有地方都建议参考孩子的父母,所以我不知道该怎么做。 有人可以就此给我一些建议。
这是因为问题有答案并且答案有对问题的引用吗?
是的。 它不能被序列化。
编辑:请参阅 Tallmaris 的回答和 OttO 的评论,因为它更简单并且可以全局设置。
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
旧答案:
将 EF 对象Question
投影到您自己的中间或 DataTransferObject。 然后可以成功序列化此 Dto。
public class QuestionDto
{
public QuestionDto()
{
this.Answers = new List<Answer>();
}
public int QuestionId { get; set; }
...
...
public string Title { get; set; }
public List<Answer> Answers { get; set; }
}
就像是:
public IList<QuestionDto> GetQuestions(int subTopicId, int questionStatusId)
{
var questions = _questionsRepository.GetAll()
.Where(a => a.SubTopicId == subTopicId &&
(questionStatusId == 99 ||
a.QuestionStatusId == questionStatusId))
.Include(a => a.Answers)
.ToList();
var dto = questions.Select(x => new QuestionDto { Title = x.Title ... } );
return dto;
}
您也可以在Application_Start()
尝试此操作:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
它应该可以解决您的问题,而不会遇到很多麻烦。
ReferenceLoopHandling.Ignore
代替。
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
如果使用 OWIN,请记住,不再需要 GlobalSettings! 您必须在传递给 IAppBuilder UseWebApi 函数(或您所在的任何服务平台)的 HttpConfiguration 对象中修改相同的设置
看起来像这样。
public void Configuration(IAppBuilder app)
{
//auth config, service registration, etc
var config = new HttpConfiguration();
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//other config settings, dependency injection/resolver settings, etc
app.UseWebApi(config);
}
在 ASP.NET Core 中,修复如下:
services
.AddMvc()
.AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
ASP.NET Core Web-API (.NET Core 2.0):
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MvcJsonOptions>(config =>
{
config.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
}
如果使用 DNX / MVC 6 / ASP.NET vNext 等等,甚至HttpConfiguration
都丢失了。 您必须在Startup.cs
文件中使用以下代码来配置格式化程序。
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().Configure<MvcOptions>(option =>
{
//Clear all existing output formatters
option.OutputFormatters.Clear();
var jsonOutputFormatter = new JsonOutputFormatter();
//Set ReferenceLoopHandling
jsonOutputFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
//Insert above jsonOutputFormatter as the first formatter, you can insert other formatters.
option.OutputFormatters.Insert(0, jsonOutputFormatter);
});
}
使用这个:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore
对我不起作用。 相反,我创建了一个新的简化版本的模型类来测试,结果很好。 这篇文章讨论了我在模型中遇到的一些问题,这些问题对 EF 很有用,但不能序列化:
http://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-4
ReferenceLoopHandling.Ignore 对我不起作用。 我能绕过它的唯一方法是通过代码删除链接回我不想要的父级并保留我做的那些。
parent.Child.Parent = null;
对于使用 .Net Framework 4.5 的新 Asp.Net Web 应用程序:
Web Api:转到 App_Start -> WebApiConfig.cs:
应该是这样的:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// ReferenceLoopHandling.Ignore will solve the Self referencing loop detected error
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//Will serve json as default instead of XML
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
作为 ASP.NET Core 3.0 的一部分,团队不再默认包含 Json.NET。 您可以在 [包括 Json.Net 到 netcore 3.x][1] https://github.com/aspnet/Announcements/issues/325 中阅读更多相关信息
使用延迟加载可能会导致错误: services.AddDbContext(options => options.UseLazyLoadingProxies()... 或 db.Configuration.LazyLoadingEnabled = true;
修复:添加到 startup.cs
services.AddControllers().AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
由于延迟加载,您会收到此错误。 因此我的建议是从财产中删除虚拟钥匙。 如果您正在使用 API,那么延迟加载对您的 API 健康不利。
无需在配置文件中添加额外的行。
public class Question
{
public int QuestionId { get; set; }
public string Title { get; set; }
public ICollection<Answer> Answers { get; set; }
}
public class Answer
{
public int AnswerId { get; set; }
public string Text { get; set; }
public int QuestionId { get; set; }
public Question Question { get; set; }
}
我发现这个错误是在我生成现有数据库的 edmx(定义概念模型的 XML 文件)时引起的,并且它具有到父表和子表的导航属性。 我删除了所有到父对象的导航链接,因为我只想导航到子对象,问题就解决了。
实体数据库 = 新实体()
db.Configuration.ProxyCreationEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
您可以动态创建新的子集合来轻松解决此问题。
public IList<Question> GetQuestions(int subTopicId, int questionStatusId)
{
var questions = _questionsRepository.GetAll()
.Where(a => a.SubTopicId == subTopicId &&
(questionStatusId == 99 ||
a.QuestionStatusId == questionStatusId))
.Include(a => a.Answers).Select(b=> new {
b.QuestionId,
b.Title
Answers = b.Answers.Select(c=> new {
c.AnswerId,
c.Text,
c.QuestionId }))
.ToList();
return questions;
}
上面答案中的所有配置都不适用于 ASP.NET Core 2.2。
我在我的虚拟导航属性上添加了JsonIgnore
属性。
public class Question
{
public int QuestionId { get; set; }
public string Title { get; set; }
[JsonIgnore]
public virtual ICollection<Answer> Answers { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.