I Swashbuckle v.5.3中的操作过滤器更改



我试图将两个自定义MediaType添加到同一方法中。为了添加这个任务,我们可以使用[Produuces((]属性,但如果我们想在同一个控制器中有两个GET方法,我们会在swagger 中得到这个错误

SwaggerGeneratorException:冲突的方法/路径组合"获取api/authors/{authorId}/books/{bookId}";用于操作-Library.API.Controllers.BooksController.GetBook(Library.API(、Library.API.Controllers.BooksCoontroller.GetBookWithConcatenatedAuthorName(Library.OpenAPI(。操作需要Swagger/OpenAPI 3.0的唯一方法/路径组合。使用冲突操作解决方案作为解决

在Swashbucklev5测试版中,我们可以使用此IOperationFilter并添加自定义MediaType架构并使用此代码

public class GetBookOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.OperationId != "GetBook")
{
return;
}
operation.Responses[StatusCodes.Status200OK.ToString()].Content.Add(
"application/vnd.marvin.bookwithconcatenatedauthorname+json",
new OpenApiMediaType()
{
Schema = context.SchemaRegistry.GetOrRegister(typeof(BookWithConcatenatedAuthorName))
});
}
}

但我们不能在Swashbuckle v5.6.3 中使用此代码

请帮我解决这个问题

我回复了这个代码并解决了我的问题。

if (context.ApiDescription.ActionDescriptor.RouteValues["action"] != "GetBook")
{
return;
}
var schema = context.SchemaGenerator.GenerateSchema(typeof(BookWithConcatenatedAuthorName), context.SchemaRepository);

if (operation.Responses.Any(a=> a.Key==StatusCodes.Status200OK.ToString()))
{
operation.Responses[StatusCodes.Status200OK.ToString()].Content.Add(
"application/vnd.marvin.bookwithconcatenatedauthorname+json",
new OpenApiMediaType() { Schema = schema });
}

最新更新