我在beta6中使用ASP.NET MVC。
在我的Startup.cs中,我有以下代码:
services.AddMvc().Configure<MvcOptions>(o =>
{
o.OutputFormatters.RemoveAll(formatter => formatter.GetType() == typeof(JsonOutputFormatter));
var jsonOutputFormatter = new JsonOutputFormatter
{
SerializerSettings = { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore }
};
o.OutputFormatters.Insert(0, jsonOutputFormatter);
});
在我的控制器中我有:
public async Task<JsonResult> Get()
{
var result = new DataTablesResult();
List<MyClass> myClass = await _Repository.GetListMyClass();
result.Data = new List<dynamic>(myClass);
var resultado = new
{
data = result.Data.ToArray()
};
return Json(resultado);
}
在我使用6 beta 4中的Asp.Net MVC并且相同的代码工作之前。
知道可能出现什么问题吗?
我的路线:
app.UseMvc(routes =>
{
// add the new route here.
routes.MapRoute(name: "config",
template: "{area:exists}/{controller}/{action}",
defaults: new { controller = "Home", action = "Index" });
routes.MapRoute(
name: "configId",
template: "{area:exists}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index" });
routes.MapRoute(name: "platform",
template: "{area:exists}/{controller}/{action}",
defaults: new { controller = "Home", action = "Index" });
routes.MapRoute(name: "platformByUser",
template: "{area:exists}/{controller}/{action}/{userId}");
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
// Uncomment the following line to add a route for porting Web API 2 controllers.
// routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
});
答案 0 :(得分:0)
我注意到您将属性 ReferenceLoopHandling 设置为 Newtonsoft.Json.ReferenceLoopHandling.Ignore 。据我所知,the settings for the JSON output formatter and for JsonResult are now separate。 如果MyClass有循环,则Json.net中会发生错误。
检测到自我参考循环
在这种情况下有两种解决方案:
1)使用控制器方法的自定义序列化设置:
var settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
return Json(result, settings);
2)在JchoResult和Startup中的格式化程序之间配置共享设置:
public void ConfigureServices(IServiceCollection services)
{
//some configuration
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
}
我希望这会对你有所帮助