Posted by Abhishek on December 12, 2019
In this blog post, we will learn how to create an ASP.NET Core 2.2 Web API with Swagger feature. Swashbuckle is an open source project that generates swagger documents for Web API’s. Swagger makes it really easy for people to understand an API and provides a playground to interact with the Web API. Thus it ensures a rich interactivity interface for users, provides better understandable API documentation, makes it easy to discover the API and helps the developers build API’s that confirm to OpenAPI standards.
Firstly, open Visual Studio 2019
Choose “ASP.NET Core Web Application” from project templates and click Next
Provide a Project Name and click “Create” button. In my case, the project name is “TestAPI”.
Choose the application type as “Web Application (Model-View-Controller)“. Make sure that the .NET Core version selected is “ASP.NET Core 2.2“. Also make sure to click the “Change” link next to Authentication [on the right] and select “Individual User Accounts“. As a best practice, Web API’s needs to have authentication. We will not select Docker because it’s not in the scope of this blog. Now click the “Create” button and wait for Visual Studio to set up your project.
Once Visual Studio has done setting up the project, you will see the project structure in Solution Explorer as shown below.
Now delete the following things from the project in the Solution Explorer.
Controllers/HomeController.cs (delete this file only)
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
.AddDefaultUI(UIFramework.Bootstrap4)
app.UseDatabaseErrorPage();
app.UseCookiePolicy();
The final code in Startup.cs should look like as shown below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TestAPI.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace TestAPI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Now, add an empty MVC Controller under Controllers folder and name it as “UserController”. Edit the UserController code with a GET method as shown below (this is to test if our controller would work like an API)
using Microsoft.AspNetCore.Mvc;
namespace TestAPI.Controllers
{
public class UserController : Controller
{
[HttpGet("api/user")]
public IActionResult Get()
{
return Ok(new { Name = "Test Name" });
}
}
}
Save and build the project Now, right click on the “TestAPI” project and select Properties.
In the Project Properties, navigate to Debug tab and hit the “Delete” button next to the Profile. When you hit the Delete button, the Profile that shows “IIS Express” will change to “TestAPI” & Launch will also change to “Project”. We did this so that when we run this project, it runs as a console application. Why? Because for a Web API, you don’t have a User Interface to work with.
Click on “Ctrl+S” to save the project properties and close this tab. Now, run this project by clicking the “F5” button on keyboard. If an SSL certificate confirmation box opens, click “Yes”.
You will see that a command line box opens and eventually a browser will also open. It is in this command window that the API starts and runs. The browser window opens so that you can execute the API URL and check for yourself if the API is working or not. [Do not close the command window. If you do so, the project will stop running and you have to run it again by pressing F5] On the browser window, you would see an error. This is because the API controller that we wrote is only available in the URL alias “/api/user“.
So, change the URL to “https://localhost:5001/api/user” and hit Enter. You will see the data with “name” property and “Test Name” value (exactly as we configured in the Controller code). Excellent progress till now.
Now, we are ready to configure Swagger in this “TestAPI” project. Close the browser window and the command window. This stops the project from running. In the project in Visual Studio, right click on “TestAPI” project and choose “Manage NuGet Packages” option
In the Nuget Window, change the selection from “Installed” to “Browse” and type “Swashbuckle.aspnetcore” in the Search Box. Choose the “Swashbuckle.AspNetCore” package and click on “Install”
If a Preview Changes window opens, click on “OK” button
Once the installation of package is complete, right click on the “TestAPI” project in solution explorer –> go to “Add” –> select “New Folder“. Name the folder as “Options”.
Right click on “Options” folder –> go to “Add” –> select “Class”. Name the class as “SwaggerOptions.cs“. Add 3 string properties namely “JsonRoute”, “Description” and “UIEndpoint”. Save the “SwaggerOptions.cs” file by pressing Ctrl+S.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TestAPI.Options
{
public class SwaggerOptions
{
public string JsonRoute { get; set; }
public string Description { get; set; }
public string UIEndpoint { get; set; }
}
}
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)mssqllocaldb;Database=aspnet-TestAPI-8323AC48-C8C7-4C5D-95E8-97EC5F60E9B8;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"SwaggerOptions": {
"JsonRoute": "swagger/{documentName}/swagger.json",
"Description": "Test API",
"UIEndpoint": "v1/swagger.json"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "Test API", Version = "v1" });
});
In the “Configure” method, add the following lines of code at the last. Here, we are binding the values SwaggerOptions JSON properties and it’s values to SwaggerOptions class. Additionally, we configure the app with Swagger with the SwaggerOptions data.
//Here, we are binding the values SwaggerOptions JSON properties and it's values to SwaggerOptions class
var swaggerOptions = new Options.SwaggerOptions();
Configuration.GetSection(nameof(Options.SwaggerOptions)).Bind(swaggerOptions);
//Configure the Swagger with swaggerOptions data
app.UseSwagger(option => { option.RouteTemplate = swaggerOptions.JsonRoute; });
app.UseSwaggerUI(option =>
{
option.SwaggerEndpoint(swaggerOptions.UIEndpoint, swaggerOptions.Description);
});
Now, build the project. It should build without any errors. Click “F5” and run the project. In the newly opened browser, change the URL to “https://localhost:5001/swagger” and hit Enter. You should now see the Swagger UI with our “/api/user” api endpoint configured.
You can now test the API in Swagger UI by clicking on the “/api/user” and hit the “Try it out” button and “Execute” button. This will invoke the “/api/user” endpoint and return the response with “name” property and “Test Name” value.
Hope this blog was helpful to you in understanding Swagger and its configurations from scratch. Happy Coding 🙂