Swagger(C#的Swashbuckle)显示Mongo ObjectId为多个字段,而不是单个字符串

问题描述 投票:0回答:1

我有带有ObjectId参数的控制器方法:

[ProducesResponseType(200, Type = typeof(Test))]
[HttpGet]
[Route("{id}")]
public IActionResult Get(ObjectId id)
{...

对于此API方法,swagger生成具有复杂ObjectId模型和字符串ID而不是单个字符串参数的形式:swagger generated form如何删除多余的字段并仅保留字符串ID?

c# mongodb swagger swashbuckle objectid
1个回答
0
投票

可以过滤表格形式生成器的输出字段:

public class SwaggerOperationFilter : IOperationFilter
{
    private readonly IEnumerable<string> objectIdIgnoreParameters = new[]
    {
        nameof(ObjectId.Timestamp),
        nameof(ObjectId.Machine),
        nameof(ObjectId.Pid),
        nameof(ObjectId.Increment),
        nameof(ObjectId.CreationTime)
    };

    public void Apply(Operation operation, OperationFilterContext context)
    {
        operation.Parameters = operation.Parameters.Where(x =>
            x.In != "query" || objectIdIgnoreParameters.Contains(x.Name) == false
        ).ToList();
    }
}

并在Startup.cs中使用此过滤器:

public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSwaggerGen(options =>
        {
            ...
            options.OperationFilter<SwaggerOperationFilter>();
        });
...

结果,我们只有ID字段:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.