接下来自我引用循环json

时间:2015-02-22 20:40:32

标签: c# asp.net json asp.net-mvc

当signalr向客户端发送响应时,有时会出现自引用循环。我怎样才能在MVC5中解决这个问题?

在我使用的正常ASP.NET mvc 5项目中:

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling 
     = Newtonsoft.Json.ReferenceLoopHandling.Serialize;     
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling 
     = Newtonsoft.Json.PreserveReferencesHandling.Objects;

如何在ASP.NET mvc 6 Vnext项目中执行此操作?

3 个答案:

答案 0 :(得分:1)

当前构建器中的核心更改: https://github.com/aspnet/Mvc/commit/9d89a8cac3cb5fb6b1aa7138814957708c2c22ca

        services.AddMvc().AddJsonOptions(options =>
        {
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; ;
        });

答案 1 :(得分:0)

Startup课程中:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().Configure<MvcOptions>(options => {

        var jsonFormatter = options.OutputFormatters
            .OfType<JsonOutputFormatter>()
            .First();

        jsonFormatter.SerializerSettings.ReferenceLoopHandling =
            ReferenceLoopHandling.Serialize;
        jsonFormatter.SerializerSettings.PreserveReferencesHandling =
            PreserveReferencesHandling.Objects;

    });
}

答案 2 :(得分:0)

我使用下面的代码解决了这个问题。

services.AddMvc().Configure<MvcOptions>(options => {
    var jsonFormatter = (JsonOutputFormatter)options.OutputFormatters
    .Where(o => o.Instance.GetType() == typeof(JsonOutputFormatter)).First().Instance;
    jsonFormatter.SerializerSettings.ReferenceLoopHandling =
         ReferenceLoopHandling.Ignore;

});