Swagger.json 文件生成后如何以编程方式访问它
How do you programmatically access the Swagger.json file after it has been generated
我正在尝试创建一个动态 rest api,它使用 Swagger 作为 .NetCore 中的文档(使用 Swashbuckle.AspNetCore)。
动态是指只有 1 个控制器和 1 个可能的响应开始,但用户可以通过 POST 向服务添加 "end points",然后控制器可以转换新路由以相应地响应
为此,我需要能够访问和更改 swagger.json 文件以及让 UI 更改以反映更改 - 这可能吗?如果是怎么办?
注意:我知道我可以通过导航到 /{documentname}/swagger.json 来访问和查看 swagger 文档,但这不允许我更改它
您可以使用自定义过滤器扩展、过滤和自定义架构:
https://github.com/domaindrivendev/Swashbuckle.AspNetCore#extend-generator-with-operation-schema--document-filters
我确实用它来为每个请求装饰更多 header-fields(比如授权 header)。我不确定它是否适用于整个端点。但也许值得一试。
更新(已编辑)
这是添加整个端点的示例 IDocumentFilter:
private class DocumentFilterAddFakes : IDocumentFilter
{
private PathItem FakePathItem(int i)
{
var x = new PathItem();
x.Get = new Operation()
{
Tags = new[] { "Fake" },
OperationId = "Fake_Get" + i.ToString(),
Consumes = null,
Produces = new[] { "application/json", "text/json", "application/xml", "text/xml" },
Parameters = new List<IParameter>()
{
new NonBodyParameter() // Can also be BodyParameter
{
Name = "id",
@In = "path",
Required = true,
Type = "integer",
Format = "int32",
@Default = 8
}
},
};
x.Get.Responses = new Dictionary<string, Response>();
x.Get.Responses.Add("200", new Response() { Description = "OK", Schema = new Schema() { Type = "string" } });
return x;
}
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
for (int i = 0; i < 10; i++)
swaggerDoc.paths.Add("/Fake/" + i + "/{id}", FakePathItem(i));
}
}
我正在尝试创建一个动态 rest api,它使用 Swagger 作为 .NetCore 中的文档(使用 Swashbuckle.AspNetCore)。 动态是指只有 1 个控制器和 1 个可能的响应开始,但用户可以通过 POST 向服务添加 "end points",然后控制器可以转换新路由以相应地响应
为此,我需要能够访问和更改 swagger.json 文件以及让 UI 更改以反映更改 - 这可能吗?如果是怎么办?
注意:我知道我可以通过导航到 /{documentname}/swagger.json 来访问和查看 swagger 文档,但这不允许我更改它
您可以使用自定义过滤器扩展、过滤和自定义架构: https://github.com/domaindrivendev/Swashbuckle.AspNetCore#extend-generator-with-operation-schema--document-filters
我确实用它来为每个请求装饰更多 header-fields(比如授权 header)。我不确定它是否适用于整个端点。但也许值得一试。
更新(已编辑)
这是添加整个端点的示例 IDocumentFilter:
private class DocumentFilterAddFakes : IDocumentFilter
{
private PathItem FakePathItem(int i)
{
var x = new PathItem();
x.Get = new Operation()
{
Tags = new[] { "Fake" },
OperationId = "Fake_Get" + i.ToString(),
Consumes = null,
Produces = new[] { "application/json", "text/json", "application/xml", "text/xml" },
Parameters = new List<IParameter>()
{
new NonBodyParameter() // Can also be BodyParameter
{
Name = "id",
@In = "path",
Required = true,
Type = "integer",
Format = "int32",
@Default = 8
}
},
};
x.Get.Responses = new Dictionary<string, Response>();
x.Get.Responses.Add("200", new Response() { Description = "OK", Schema = new Schema() { Type = "string" } });
return x;
}
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
for (int i = 0; i < 10; i++)
swaggerDoc.paths.Add("/Fake/" + i + "/{id}", FakePathItem(i));
}
}