Search code examples
c#mongodbswaggerswashbuckleobjectid

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


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: swagger generated form How I can remove extra fields and keep only string Id?


Solution

  • 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: enter image description here