我有带有ObjectId
参数的控制器方法:
[ProducesResponseType(200, Type = typeof(Test))]
[HttpGet]
[Route("{id}")]
public IActionResult Get(ObjectId id)
{...
对于此API方法,swagger生成具有复杂ObjectId模型和字符串ID而不是单个字符串参数的形式:如何删除多余的字段并仅保留字符串ID?
可以过滤表格形式生成器的输出字段:
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>();
});
...