如何解决当类具有循环引用时,Swashbuckle会引发StackOverFlow异常
我有一个像下面这样的控制器,在B类中有循环引用。
之所以发生这种情况,是因为Swashbuckle的jsonserilalizer的设置设置为
ReferenceLoopHandling = ReferenceLoopHandling.Error
,但我找不到任何方法可以覆盖此设置。
我正在ASP.NET MVC应用程序中使用Swashbuckle 5.6.0。
public class IssueController : ApiController
{
[HttpGet]
[Route("A")]
public A Get(A input)
{
return new A();
}
}
public class A
{
public virtual B prop1 { get; set; }
}
public class B
{
public virtual B Parent { get; set; }
}
解决方法
在我的例子中,事实证明 Stackoverflow 异常不是由 jsonserializer 引起的,而是由上一步引起的(在 json 序列化之前创建 Swashbuckle 模式时)。 Circle References 似乎还不适用于 Swashbuckle(在 Swashbuckle 中,它似乎已修复)。要解决此问题,您必须复制 HandleFromUriParamsRecurseSave
并将其(与其他过滤器一起)添加到操作中:
private static SwaggerDocument BuildSwaggerDocument()
{
...
var operationFilters = new List<IOperationFilter> {
new HandleFromUriParamsRecurseSave(20),...
};
}
在复制的 HandleFromUriParamsRecurseSave 中,只需添加一个适合您的情况的 maxrecurselength 属性,您就不应该再出现 StackOverflow 错误:
private void ExtractAndAddQueryParams(
Schema sourceSchema,string sourceQualifier,bool? sourceRequired,SchemaRegistry schemaRegistry,ICollection<Parameter> operationParams)
{
foreach (var property in sourceSchema.properties)
{
...
var recurseCount = sourceQualifier.Count(t => t == '.');
if (schema.@ref != null && recurseCount < _maxRecurseLength)
{
ExtractAndAddQueryParams(schemaRegistry.Definitions[schema.@ref.Replace("#/definitions/","")],sourceQualifier + ToCamelCase(property.Key) + ".",flag,schemaRegistry,operationParams);
}
else
{
...
}
}
}
}
我尝试过的另一种解决方法,但不幸的是没有解决问题,是添加一个堆栈,每次检测到循环时,只添加一次正确的架构定义(也许有人看到了问题):
private void ExtractAndAddQueryParams(
Stack<string> sourceSchemaNames,Schema sourceSchema,ICollection<Parameter> operationParams)
{
if (sourceSchemaNames.Count > _maxRecurseLength) {
return;
}
foreach (var property in sourceSchema.properties)
{
var schema = property.Value;
var readOnly = schema.readOnly;
if (readOnly != true)
{
var flag = sourceRequired == true && sourceSchema.required != null && sourceSchema.required.Contains(property.Key);
var recursionDetected = _disableRecursion && sourceSchemaNames.Contains(schema.@ref);
if (schema.@ref != null && !recursionDetected)
{
sourceSchemaNames.Push(schema.@ref);
ExtractAndAddQueryParams(sourceSchemaNames,schemaRegistry.Definitions[schema.@ref.Replace("#/definitions/",operationParams);
sourceSchemaNames.Pop();
}
else
{
...
if (recursionDetected) {
partialSchema.type = "object";
partialSchema.@ref = schema.@ref;
}
operationParams.Add(partialSchema);
}
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。