Swagger Documentation for.Net Core API.

The following are the procedures for creating a.NET Core API with Swagger documentation.

1. Begin by creating a new.NET Core project in Visual Studio or with the.NET Core CLI.

2. Run the following command in the Package Manager Console to install the Swashbuckle.AspNetCore NuGet package:

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 sets up the Swagger generator and creates a Swagger document called “My API” with the version “v1.”

4. Add the following code to the Startup.cs file’s Configure function,

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

This code includes the Swagger middleware, which generates the Swagger JSON endpoint and Interface.

5. Use XML comments in your API controllers and models to offer more extensive API explanations. Add the following code to the.csproj file to allow XML documentation:

<PropertyGroup>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
    <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

This code produces an XML documentation file for your project and disables the warning about lacking XML comments.

6. Launch your API project and browse to the Swagger UI page at https://localhost:port/swagger/index.html, where port is your API project’s port number. You should look at the Swagger-generated API documentation.

Summary
That’s all! You have now developed a Swagger-documented.NET Core API. You may personalise the Swagger document by passing more parameters to the AddSwaggerGen function, such as security definitions and operation filters.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories