Swagger is a robust API documentation and testing tool for ASP.NET Core applications. It creates interactive API documentation to help developers understand and work with your APIs. In other circumstances, though, you may want to expose only certain APIs to Swagger documentation while hiding others. This is useful when you have internal or administrative APIs that should not be accessible to outside users. With actual examples, we will look at how to selectively reveal only specified APIs on Swagger in ASP.NET Core.
Step 1: Begin by creating an ASP.NET Core Web API Project
If you don't already have an ASP.NET Core Web API project, use the following command to create one.
dotnet new webapi -n MyApi
Step 2. Install Swashbuckle.AspNetCore
To enable Swagger documentation in your ASP.NET Core project, you need to install the Swashbuckle.AspNetCore NuGet package. You can do this using the Package Manager Console or by running the following command.
Step 3. Configure Swagger
Next, open the Startup.cs file in your project and add the following code to the ConfigureServices and Configure methods.
This code configures Swagger with a default documentation endpoint.
To selectively show only specific APIs on Swagger, you can use the [ApiExplorerSettings] attribute on your controller methods. Here's an example.
In this example, the HiddenApi method is decorated with [ApiExplorerSettings(IgnoreApi = true)], which tells Swagger to ignore this API during documentation generation. The VisibleApi method, on the other hand, is not decorated, so it will be visible on Swagger.
Now that you've configured Swagger and marked specific APIs as hidden or visible, you can run your ASP.NET Core application using the following command:
Your application will start, and you can access Swagger documentation by navigating to https://localhost:5001/swagger (or the respective URL for your project).
In this article, we've learned how to selectively show only specific APIs on Swagger in an ASP.NET Core application. By using the [ApiExplorerSettings] attribute to mark certain APIs as hidden or visible, you can control which endpoints are documented and exposed via Swagger. This can be particularly useful when you want to keep administrative or internal APIs hidden from external users while providing comprehensive documentation for the APIs that should be accessible to everyone.
0 comments:
Post a Comment