Home > Software engineering >  Asp.net Core Swagger : How to show APIs of type GET
Asp.net Core Swagger : How to show APIs of type GET

Time:04-13

How can I show only APIs of type GET in Swagger page and hide others? I found that the attribute [ApiExplorerSettings(IgnoreApi = true)] can hide the API from Swagger page,
but I have lot of APIs to hide and I need an approach to hide the APIs depending on its HTTP type. I've tried this approach :

 public class SwaggerFilter : IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            var nonGetPaths = swaggerDoc.Paths.Where(x => x.Value.Operations.First().Key != OperationType.Get);
            var count=nonGetPaths.Count();
            foreach (var item in nonGetPaths)
            {
                swaggerDoc.Paths.Remove(item.Key);
            }
        }
    }

but it didn't work

CodePudding user response:

Write a custom filter like this:

public class SwaggerFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        
        foreach (var path in swaggerDoc.Paths)
        {
          foreach (var key in path.Value.Operations.Keys )
          {
            if (key != OperationType.Get)
            {
                swaggerDoc.Paths.Remove(path.Key);
            }
          }
       }
       
    }
}

Then configure in program.cs(.Net 6)

//.......
builder.Services.AddSwaggerGen(x=>x.DocumentFilter<SwaggerFilter>());
//......

I don't add [ApiExplorerSettings(IgnoreApi = true)] in my apicontroller and it works all fine.

But, Make sure Get endpoint and other type of endpoint have different route in the same controller, You can add attribute route like [HttpGet("/get")] on Get endpoint. If you just write like this in the same controller:

       [HttpPost]
        public IActionResult Post()
        {
            return Ok();
        }

        [HttpGet]
        public IActionResult Get()
        {
            return NotFound();
        }

Get and Post endpoint will have the same path. swaggerDoc.Paths.Remove(xxx); will remove all of them.

Reuslt:

Before

enter image description here

After

enter image description here

  • Related