我正在制作 Core 3.1 Web API 并使用杰森补丁 https://learn.microsoft.com/en-us/aspnet/core/web-api/jsonpatch?view=aspnetcore-3.1创建 PATCH 操作。我有一个名为Patch
其中有一个JsonPatchDocument
范围。这是该操作的签名:
[HttpPatch("{id}")]
public ActionResult<FileRecordDto> Patch(int id, [FromBody] JsonPatchDocument<FileRecordQueryParams> patchDoc)
据我了解,该参数需要接收以下结构的 JSON 数据,我已使用该操作成功测试了该数据:
[
{
"op": "operationName",
"path": "/propertyName",
"value": "newPropertyValue"
}
]
However, the action's documentation generated by Swagger https://swagger.io/ has a different structure:
我不熟悉这个结构,甚至"value"
其中缺少属性,这是JsonPatchDocument
对象有。每个修补的例子replace
我见过的操作有第一个结构。
为什么 Swagger 会生成替代结构JsonPatchDocument
PATCH 端点的请求正文中的对象?我该如何解决?
The NuGet package installed for Swagger:
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>());
Result:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)