【发布时间】:2026-02-07 23:25:02
【问题描述】:
我最近开始在我的 EF Core 项目中使用 Swagger/Swashbuckle。
当我将补丁 API 添加到文档时,请求正文的示例值/架构显示的是 Delta 的详细信息,而不是我的对象。由于它是需要发布的对象属性的子集,有没有办法显示我的对象架构?
swagger 和 API 的签名如下。
/// <summary>
/// Updates the provided Absence Reason.
/// </summary>
/// <remarks>
/// Runs bespoke Patch/Validation logic.
/// Updates the Absence Reason then returns the record.
/// </remarks>
/// <param name="key" required="true">Id of the Absence Reason being updated.</param>
/// <param name="delta" required="true">A delta of the updated Absence Reason record.</param>
/// <returns>Returns the created Absence Reason</returns>
/// <response code="204">Returns the updated Absence Reason.</response>
/// <response code="400">Invalid Absence Reason Record, Missing Row Version etc.</response>
/// <response code="404">Absence Reason not found.</response>
/// <response code="412">Record has been updated since the version provided.</response>
[ApiExplorerSettings]
[HttpPatch("odata/[controller]({key})")]
[Produces("application/json")]
[ProducesResponseType(typeof(AbsenceReason), StatusCodes.Status204NoContent)]
[ProducesResponseType(400)]
[ProducesResponseType(404)]
[ProducesResponseType(412)]
[Authorize(Policy = AuthPolicyNames.GOIAdminRole)]
public IActionResult Patch([FromODataUri] long key, Delta<AbsenceReason> delta)
编辑以添加其他信息以响应 AlFranco
您代码中的 _assemblyName 是 “Microsoft.AspNetCore.OData,版本=7.4.1.0,文化=中性,PublicKeyToken=31bf3856ad364e35”
VS 文档创建的精简后的 XML 文件是:
<member name="M:ESRGOI.Controllers.AbsenceReasonsController.Patch(System.Int64,Microsoft.AspNet.OData.Delta{ESRGOI.Models.AbsenceReason})">
<summary>
Updates the provided Absence Reason.
</summary>
<param name="key" required="true">Id of the Absence Reason being updated.</param>
<param name="delta" required="true">A delta of the updated Absence Reason record.</param>
</member>
编辑 2 好的,我已经根据 AlFranco 的回复想出了一个解决方案。
应该注意在 Swagger 中我的模型不包含命名空间。我最初尝试包含命名空间,但收到以下错误: /components/schemas/ESRGOI.Models.AbsenceReason 在文档中不存在
public class DeltaOperationFilter : IOperationFilter
{
private const string _deltaParam = "Delta";
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.RequestBody == null) return;
var deltaTypes =
operation.RequestBody
.Content
.Where(x => x.Value.Schema.Reference.Id.EndsWith(_deltaParam));
foreach (var (_, value) in deltaTypes)
{
var schema = value.Schema;
string model = schema.Reference.Id.Substring(0, schema.Reference.Id.Length - _deltaParam.Length);
schema.Reference.Id = model;
}
}
}
【问题讨论】:
-
嘿,我也遇到了同样的问题,你解决了吗?
-
恐怕还没有,还是希望这里有人知道答案。
标签: c# entity-framework swagger swashbuckle