排除 Swagger .NET 中的循环引用

问题描述 投票:0回答:1

我有一个项目最近迁移到.NET 8,我发现构建管道的 terraform 脚本无法生成 Swagger JSON,因此无法将其添加到我们的 APIM 中。

我发现这是由循环引用引起的。 我尝试在虚拟项目中重新创建相同的问题,以查看是否某些依赖项导致了此问题,但这似乎是一个通用问题,因此用例和问题是相同的。一个简单的修复方法是从类中删除循环引用本身,但这在我们的用例中并不是真正的选项。我见过的一件事是使用 System.Text.Json 并在属性上使用 [JsonIgnore] 注释,但是团队正在放弃使用它并倾向于 Newtonsoft.Json - 这不起作用。

在为 swagger 生成 JSON 模式时是否有其他通用方法来排除循环引用?

请注意,swagger 生成模式很好 - 然而循环引用是我无法为该服务启动 swagger 的罪魁祸首。

简单的例子:

using Newtonsoft.Json;

namespace CircularReferenceFix;

public class WeatherForecast
{
public DateOnly Date { get; set; }

public int TemperatureC { get; set; }

public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

public string? Summary { get; set; }

// Include Circular reference to test
[JsonIgnore]
public WeatherForecast NextForecast { get; set; }
}

// Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
  app.UseSwagger();
  app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
c# .net swagger swashbuckle .net-8.0
1个回答
0
投票

在 Program.cs 中添加以下内容将切换到 Newtonsoft,并包含忽略循环引用的设置

// swithces serializer from System.Text.Json to Newtonsoft 
// this will not work if switching from MVC/Controllers to Minimal API 
builder.Services.AddControllers().AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    // add additional serializer settings
});

// switches Swagger to use Newtonsoft
builder.Services.AddSwaggerGenNewtonsoftSupport();

需要其他项目参考:

<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore.Newtonsoft" Version="6.5.0" />

有关更多详细信息,请参阅以下指南:

https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-8.0#add-newtonsoftjson-based-json-format-support-2

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/README.md#systemtextjson-stj-vs-newtonsoft

© www.soinside.com 2019 - 2024. All rights reserved.