Swagger (Swashbuckle for C#) shows Mongo ObjectId as several fields instead of single string

人走茶凉 提交于 2020-03-03 07:29:31

问题


I have controller method with ObjectId params:

[ProducesResponseType(200, Type = typeof(Test))]
[HttpGet]
[Route("{id}")]
public IActionResult Get(ObjectId 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?


回答1:


Find out what answer from another story also adresses this issue:

services.AddMvc(options =>
{                    
    ...
    options.ModelMetadataDetailsProviders.Add(
        new BindingSourceMetadataProvider(typeof(ObjectId), BindingSource.Special));
});



回答2:


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();
    }
}

and use this filter in Startup.cs:

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

As the result, we have only Id field:



来源:https://stackoverflow.com/questions/59800064/swagger-swashbuckle-for-c-shows-mongo-objectid-as-several-fields-instead-of-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!