c# - 示例请求正文中 JsonPatchDocument 的 Swagger 意外 API PATCH 操作文档
问题描述
我正在制作一个 Core 3.1 Web API 并使用JsonPatch创建一个 PATCH 操作。我有一个名为的动作Patch
,它有一个JsonPatchDocument
参数。这是动作的签名:
[HttpPatch("{id}")]
public ActionResult<FileRecordDto> Patch(int id, [FromBody] JsonPatchDocument<FileRecordQueryParams> patchDoc)
据我了解,该参数需要接收以下结构的 JSON 数据,我已通过操作成功测试了该结构:
[
{
"op": "operationName",
"path": "/propertyName",
"value": "newPropertyValue"
}
]
但是, Swagger生成的操作文档具有不同的结构:
我不熟悉这种结构,甚至"value"
它也缺少JsonPatchDocument
对象所具有的属性。replace
我见过的每个修补操作的例子都有第一个结构。
JsonPatchDocument
为什么 Swagger会为 PATCH 端点的请求正文中的对象生成替代结构?我该如何解决?
解决方案
Swashbuckle.AspNetCore
不适用于这种类型JsonPatchDocument<UpdateModel>
,它不代表预期的补丁请求文件。
您需要自定义一个文档过滤器来修改生成的规范。
public class JsonPatchDocumentFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
var schemas = swaggerDoc.Components.Schemas.ToList();
foreach (var item in schemas)
{
if (item.Key.StartsWith("Operation") || item.Key.StartsWith("JsonPatchDocument"))
swaggerDoc.Components.Schemas.Remove(item.Key);
}
swaggerDoc.Components.Schemas.Add("Operation", new OpenApiSchema
{
Type = "object",
Properties = new Dictionary<string, OpenApiSchema>
{
{"op", new OpenApiSchema{ Type = "string" } },
{"value", new OpenApiSchema{ Type = "string"} },
{"path", new OpenApiSchema{ Type = "string" } }
}
});
swaggerDoc.Components.Schemas.Add("JsonPatchDocument", new OpenApiSchema
{
Type = "array",
Items = new OpenApiSchema
{
Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = "Operation" }
},
Description = "Array of operations to perform"
});
foreach (var path in swaggerDoc.Paths.SelectMany(p => p.Value.Operations)
.Where(p => p.Key == Microsoft.OpenApi.Models.OperationType.Patch))
{
foreach (var item in path.Value.RequestBody.Content.Where(c => c.Key != "application/json-patch+json"))
path.Value.RequestBody.Content.Remove(item.Key);
var response = path.Value.RequestBody.Content.Single(c => c.Key == "application/json-patch+json");
response.Value.Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = "JsonPatchDocument" }
};
}
}
}
注册过滤器:
services.AddSwaggerGen(c => c.DocumentFilter<JsonPatchDocumentFilter>());
结果:
推荐阅读
- c - C:使用“scanf”读取一行其他字符中的浮点数
- java - RecyclerView 适配器继承:ViewHolder 紧耦合
- php - 如何处理奇数数组项的未定义偏移错误?
- web-scraping - 循环时无法单击元素
- java - 你如何让 TlsServer 在 BouncyCastle 的 ServerHello 上发送会话 ID?
- bash - 为什么“grep”在使用/“/”时会出错?
- javascript - 格式化javascript代码时如何阻止vscode美化或漂亮地保留换行符?
- regex - 电话号码。第三个字符不应为 5 或 6,但仍应为数字 0-9
- c++11 - 'const' 限定符不能应用于 'std::vector
&' - xamarin - 按返回按钮从应用程序返回