Introduction
This article demonstrates how to include NSwag to your project, so that you can execute and see your web api method results in Json format.
Before we get into NSwag, we have to see what is OpenAPI and Swagger.
OpenAPI Specification
OpenAPI Specification (earlier name was Swagger Specification) is an API description format for REST APIs. This file is used to describe our entire API, including available endpoints ( /users ) and action methods on each endpoint.
Now What is Swagger?
Swagger is a set of open-source tools built with OpenAPI Specification that can help you to document and consume REST APIs.
What is NSwag?
NSwag is a Swagger/OpenAPI tool for .NET Core and other platforms written in C#.
Now we can get into how to add NSwag to our project.
Step 1
Create a new project and configure it.
Step 2
Select the .Net framework version and .Net Core version and choose as a API project (Here I took an API project for an example).
Step 3
Your new project has been created with default settings and packages.
Step 4
Run the application and confirm.
Step 5
Right Click the project --> Manage NuGet Packages
Step 6
Select Browse --> Type NSwag.AspNetCore --> Install
Step 7
Confirmation pop up for dependency packages will be installed.
Step 8
Step 9
If you check the packages folder now, NSwag has ben installed.
Step 10
This is the important setting to enable NSwag
- Register your Swagger Service under ConfigureServices method in Startup.cs
- Add Swagger generator under Configure method in in Startup.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.HttpsPolicy;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Logging;
- using Microsoft.Extensions.Options;
-
- namespace NSwag
- {
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
-
- public IConfiguration Configuration { get; }
-
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
-
-
- services.AddOpenApiDocument(c =>
- {
- c.Title = "My API";
- });
- }
-
-
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- else
- {
- app.UseHsts();
- }
-
- app.UseHttpsRedirection();
- app.UseMvc();
-
-
- app.UseOpenApi();
- app.UseSwaggerUi3();
- }
- }
- }
Step 11
Now set the startup method when we run the application.
Right click the project --> Click Properties
Choose Debug and Change the Launch browser from api/values to swagger
Step 12
Run the application. Your swagger tool is ready.
Summary
In this article, we have seen what NSwag is and how to install it in your project.