Swagger(C# 的 Swashbuckle)将 Mongo ObjectId 显示为多个字段而不是单个字符串 [英] Swagger (Swashbuckle for C#) shows Mongo ObjectId as several fields instead of single string
本文介绍了Swagger(C# 的 Swashbuckle)将 Mongo ObjectId 显示为多个字段而不是单个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有带有 ObjectId
参数的控制器方法:
I have controller method with ObjectId
params:
[ProducesResponseType(200, Type = typeof(Test))]
[HttpGet]
[Route("{id}")]
public IActionResult Get(ObjectId id)
{...
对于这个 API 方法,swagger 生成一个包含复杂 ObjectId 模型和字符串 Id 的表单,而不是单个字符串参数:如何删除额外的字段并只保留字符串 ID?
For this API method swagger generates a form with both of complex ObjectId model and string Id instead of single string param: How I can remove extra fields and keep only string Id?
推荐答案
可以过滤 swagger 表单生成器的输出字段:
It is possible to filter output fields for swagger form generator:
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
中使用此过滤器:
and use this filter in Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSwaggerGen(options =>
{
...
options.OperationFilter<SwaggerOperationFilter>();
});
...
结果,我们只有 Id 字段:
As the result, we have only Id field:
这篇关于Swagger(C# 的 Swashbuckle)将 Mongo ObjectId 显示为多个字段而不是单个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文