Here are the steps to create a .NET Core API with Swagger documentation,
1. Create a new .NET Core project in Visual Studio or using the .NET Core CLI.
2. Install the Swashbuckle.AspNetCore NuGet package by running the following command in the Package Manager Console,
Install-Package Swashbuckle.AspNetCore
3. Open the Startup.cs file and add the following code to the ConfigureServices method,
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
This code registers the Swagger generator and configures a Swagger document titled "My API" and version "v1".
4. In the Configure method of the Startup.cs file, add the following code,
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
This code adds the Swagger middleware to generate the Swagger JSON endpoint and the Swagger UI.
5. Add XML comments to your API controllers and models to provide more detailed descriptions of your API. To enable XML documentation, add the following code to the .csproj file,
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
This code generates an XML documentation file for your project and suppresses the warning for missing XML comments.
6. Run your API project and navigate to the Swagger UI page at https://localhost:{port}/swagger/index.html, where {port} is the port number of your API project. You should see the API documentation generated by Swagger.
Summary
That's it! You have now created a .NET Core API with Swagger documentation. You can customize the Swagger document by adding additional options to the AddSwaggerGen method, such as security definitions and operation filters.