Web API with .NET 5

Agenda

In this article, we will learn about RESTful WebAPI with .NET 5 (Successor of .NET Core 3.1).

  1. We will create a new WebAPI project with .NET CLI in VS Code
  2. We will see what’s new provided with .NET 5 WebAPI template

Tools

  1. Visual Studio code or any IDE that supports .NET Core SDK
  2. .NET 5 SDK

Description:

Step 1: At the very first, you need to install the required IDE as well the .NET 5 SDK.

Go to https://code.visualstudio.com/download and download VS Code for your operating system. I am going to use Mac for this demo.

C) 0 Download Visual Studio Code X + 
C code.visualstudio.com/download 
Visual Studio Code 
Docs Updates Blog 
API 
Extensions FAQ Learn 
Download Visual Studio Code 
Free and built on open source. Integrated Git, debugging and extensions. 
deb 
Download 
Windows 
Windows 7, 8, 10 
User Installer 
System Installer 
64 bit 32 bit ARM 
Debian, 
.rpm 
Red Hat, Fedora, SUSE 
Mac 
macOS 10.10+ 
Ubuntu 
.54 bit 
64 bit 
64 bit 
ARM 
ARM 
ARM 
ARM 64 
ARM 64 
ARM 
Snap Store

Now, once the visual studio code is installed, go ahead and download .NET 5 SDK from https://dotnet.microsoft.com/download.

a dotnet.microsoft.com 
Download .NET (Linux, macOS, and Windows) 
Microsoft 
.NET About 
Learn 
Architecture 
Docs 
Downloads 
Linux 
Community 
LIVE TV 
All Microsoft v 
Windows 
macOS 
Docker 
.NET 5.0 (recommended) 
Current O 
.NET is a free, cross-platform, open-source developer platform 
for building many different types of applications. 
Download .NET SDK 
All .NET downloads 
Core 
.NET Core 3.1 
LTS O 
.NET Core is a free, cross-platform, open-source developer 
platform for building many different types of applications. 
Download .NET Core SDK 
All .NET Core downloads

Step 2: Open Visual Studio Code and open Integrated terminal.

o 
EXPLORER 
> OPEN EDITORS 
v NO FOLDER OPENED 
You have not yet opened a folder. 
Open Folder 
You can also clone a repository from a 
URL. To learn more about how to use 
git and source control in VS Code 
read our docs. 
Clone Repository 
> OUTLINE 
Show All Commands 
Open File or Folder 
Open Recent 
New Untitled File 
o 
PROBLEMS 
OUTPUT DEBUG CONSOLE 
—MacBook % 
TERMINAL 
1: zsh 
@ 0 Ao

By default, integrated terminal opens automatically when VS Code starts, but if that doesn’t happen, follow the screenshot below.

Terminal Window 
New Terminal ['so'] 
Split Terminal 
Run Task... 
Run Build Task... 
Run Active File 
Run Selected Text 
Help

Step 3: Before we start with the project creation, double check the version of .NET SDK installed in your machine. 

Enter the following command and hit return.

“dotnet –info”

Please check the highlighted value which makes sure that you have .NET 5 SDK installed on your machine. 

PROBLEMS 
OUTPUT DEBUG CONSOLE 
TERMINAL 
—MacBook % dotnet ——info 
.NET SDK (reflecting any gl 
Version: 
Commit : 
5.0. 102 
71365b4d42 
Runtime Environment: 
OS Name: 
Mac OS X 
OS Version: 
11.0 
OS Platform: Darwin 
RID: 
Base Path: 
osx. 11. ø-x64 
/us r/ local/ sha re/dotnet/sdk/5.0.102/ 
Host (useful for support): 
Version: 5.0.2 
Commit : 
cb5f173b96 
.NET SDKs installed: 
3.1.405 [/usr/local/share/dotnet/sdk] 
5.0.102 [/usr/local/share/dotnet/sdk] 
.NET runtimes installed: 
1 
1: zsh 
Make sure you have 
5.0 SDK installed 
Microsoft.AspNetCore.App 3.1.11 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App] 
Microsoft.AspNetCore.App 5.0.2 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App] 
Microsoft.NETCore.App 3.1.11 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App] 
Microsoft.NETCore.App 5.0.2 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App] 
To install additional .NET runtimes or SDKs: 
https : //aka. ms/dotnet—download

Step 4: Change the current directory of your terminal to the directory where you want to create a new project. Once you move to the desired directory, enter the following command to create a new WebAPI project.

“dotnet new webapi -o dotnet5api”

PROBLEMS 
OUTPUT DEBUG CONSOLE TERMINAL 
-MacBook Projects % dotnet new weba i —o dotnet5a i 
1: zsh 
(in 273 ms). 
x 
The template "ASP .NET Core Web API' was created-success u y. 
Processing post—creation actions... 
Running 'dotnet restore' on dotnet5api/dotnet5api. csproj . .. 
Determining projects to restore. .. 
Restored /Users/ 
(Documents/Proj ects/dotnet5api/dotnet5api. csp roj 
Restore succeeded.

The above command will create a new webapi project with name “dotnet5api”. 

  1. “webapi” is a keyword for .NET CLI to know that we want to create a project for webapi template.
  2. “-o” stands for options that we want to pass to the new project creation template.
  3. “dotnet5api” is the name of the project that we want to create.
Projects 
Favourites 
O Recents 
Google Drive 
Desktop 
B Documents 
> 
dotnet5api 
000 
000

Below are the files that will be generated with the new project template.

> 
dotnet5api 
00 
dotnet5api.csproj 
000 
000 
.cs 
Program.cs 
appsettings.Devel 
opment.json 
Properties 
appsettings.json 
.cs 
Startup.cs 
Controllers 
.cs 
WeatherForecast. 
cs 
obj

Step 5: Once the project is created, open the folder in VS code IDE.

o 
EXPLORER 
> 
OPEN EDITORS 
v NO FOLDER OPENED 
You have not yet opene 
Open Folder 
older. 
You can also clone a repository from a 
URL. To learn more about how to use 
git and source control in VS Code 
read our docs. 
Clone Repository
Favourites 
O Recents 
Google D... 
Desktop 
Documents 
O Downloads 
Applicati... 
Music 
Pictures 
8 Movies 
iCloud 
O iCloud Dri... 
000 
000 
dotnet5api 
dotnet5api 
Projects 
New Folder 
appsettings.D...elopment.json 
appsettings.json 
Controllers 
dotnet5api.csproj 
obj 
Program.cs 
Properties 
Startup.cs 
WeatherForecast.cs 
Q 
Search 
Cancel

Step 6: Once the folder is opened in VS Code, open the .csproj file and you will notice two things.

You can see that TargetFramework tag shows the framework used for the project. So, our project is .NET 5 based.

Second important thing you will notice is that a package named “Swashbuckle.AspNetCore” is installed. 

But, we didn’t installed any package in the project, right? So, where it came from?

This is a new thing that comes with .NET 5 template by default. This package is used to generate automatic documentation of your API so that it makes it easy for consumption and testing. I will show more about this later in the article.

Step 7: Now let’s look after other things in the created project. 

First we go to controllers, and you will find a controller named “WeatherForecastController”. This comes by default with the project template.

  1. You will see that class name is decorated with ApiController attribute which makes this controller as REST api controller. 
  2. Then you will see the route attribute and controller is mentioned in this. It tells the WebAPI host that the endpoint name will be exposed with the same name as that of controller excluding the Controller keyword from it’s name.
  3. Also look at the ControllerBase Parent class. ControllerBase exposes API related features to the controller like HttpContext etc.
  4. Look at the Get method, it returns a list of WeatherForecast with some data generated randomly. We create new endpoints like this as per the business needs.

Step 8: Now open Startup.cs file and focus on the highlighted code.

> 
o 
EXPLORER 
OPEN EDITORS 
v DOTNET5APl 
Startup.cs — dotnet5api 
bin 
C# Startup.cs X 
C# Startup.cs > { } dotnet5api > dotnet5api.Startup > ConfigureServices(lServiceCollection services) 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
u reverences 
public void ConfigureServices(IServiceCollection services 
> 
> 
> 
> 
> 
Version = "VI" 
o 
o 
C# 
C# 
.vscode 
Controllers 
obj 
Properties 
appsettings.Development.json 
appsettings.json 
dotnet5api.csproj 
Program.cs 
Startup.cs 
WeatherForecast.cs 
serv ices. AddControllers 
serv1ces.A SwaggerGemc => 
c . Swagge rDoc ( "VI" , 
new OpenApiInfo 
// This method gets called by the runtime. 
Title = "dotnet5api", 
Use this method to configure the HTTP request pipelir 
O references 
public void 
Configure(IApplicationBuilder app, IWebHostEnvironment env 
if (env.IsDevelopment()) 
app.UseDevelo erExce tionPa e() 
app. UseSwagger() 
app.UseSwaggerUI(c c. SwaggerEndpoint("/swagger/v1/swagger. j son", "dotnet5api VI"
  1. The highlighted code in ConfigureServices injects the Swagger Documentation in the request pipeline. This will generate the API documentation.
  2. The highlighted code in Configure method instructs the WebAPI to generate the SwaggerUI for the developer  to test the functioning of API.

Step 9: That’s enough knowledge about the project. Now let’s run this and see what we get. 

Execute the below command to run the project.

“dotnet run”

PROBLEMS 
Building. .. 
OUTPUT DEBUG CONSOLE TERMINAL 
—MacBook dotnet5api % dotnet run 
1: dotnet 
. Microsoft. Hosting. Lifetime [0] 
Now listening on: https://localhost:5ØØ1 
. Microsoft. Hosting. Lifetime [0] 
Now listening on: http://localhost:5ØØØ 
. Microsoft. Hosting. Lifetime [0] 
Application started. Press Ctrl+C to shut down. 
. Microsoft. Hosting. Lifetime [0] 
Hosting environment: Development 
. Microsoft. Hosting. Lifetime [0] 
Content root path: /Users/ 
/Documents/Projects/dotnet5api

The above screenshot states that localhost ports are active for this project. So we can head over to the mentioned URL and test the WebAPI.

Go to https://localhost:5001/swagger in your browser.

C) O Swagger UI 
C localhost:5001/swagger/index.html 
Swagger 
supported by SMARTBEAR 
dotnet5api 
/swagger/vl /swagger.json 
WeatherForecast 
I dotnet5api VI 
Select a definition 
OAS3 
GET 
/WeatherForecast 
Schemas 
WeatherForecast

As you can see, we get a beautiful layout with the controller name and endpoints.

Expand the controller name and follow the steps mentioned in below screenshot.

WeatherForecast 
GET 
/WeatherForecast 
Parameters 
No parameters 
Execute 
Responses 
Curl 
2 
-H 
"accept : 
Clear 
text/plain" 
curl -X GET "https ://localhost: 5ØØ1/WeatherForecast" 
Request URL 
https : / / localhost : 5001 / WeatherForecast 
Server response 
Code 
200 
Respons 
Code 
200 
Details 
Response body 
" date 
"temperatureC" : 
12, 
"temperatureF" : 
53, 
"sumary": "Sweltering" 
" date 
"temperatureC : 
"temperatureF" : 
22, 
"sumary": "Sweltering" 
" date 
"temperatureC" : 
37, 
"temperatureF" : 
98, 
"sumary": "Bracing" 
" date 
"temperatureC : 
"temperatureF" : 
24, 
"sumary": "Bracing" 
Response headers 
content—type: application/ j son; 
date: sun31 Jan 2021 03:42:53 GMT 
server: Kestrel 
transfer—encoding: chunked 
Description 
Success 
Media type 
text/plain 
Controls Accept header. 
Example Value I Schema 
" date 
"temperatureC" : 
o, 
"temperatureF" : 
o, 
"sumary": "string" 
1 
Cancel 
Links 
No links

The above screenshot shows the response that the API endpoint returns. 

If you see, we get the list of WeatherForecast as returned by GET method in the controller. 

You can even the Request and Response Headers. This is the beauty of the Swagger documentation.

Request URL 
ttps • 
ca 
os

If you hit the Request URL directly in your browser’s address bar, you will see the response data but not upto the extent which swagger exposed.

[ {"date • ' 
O O Swagger UI 
x https://localhost:5001/Weathe 
C localhost:5001/WeatherForecast 
30 " , " temperatureC" : 37 , " temperatureF" : 98, " surnmary" : "Freezing" , { "date • ' 
30 " , " temperatureC" : 13, " temperatureF" : 55, " surnmary" : " Sweltering" , { " date • 
30 " , " temperatureC" : 29 , " temperatureF" : 84 , " summary" : "Mild" } , { " date • 
" . " 2021-02- 
30 " , " temperatureC" : 29 , " temperatureF" : 84 , " surnmary" : "Balmy" , { " date • 
" . " 2021-02- 
" . '2021-02- 
" . " 2021-02- 
30 " , " temperatureC " : 20 , " temperatureF" : 67 , " surnmary" : " Balmy" ]

Step 10: Now as you have seen the functioning of the API, now let’s see where the ports and the configuration is defined in the project.

Go to Properties folder –> launchSettings.json. 

o 
EXPLORER 
> 
OPEN EDITORS 
v DOTNET5APl 
v .vscode 
launchSettings.json — dotnet5api 
o 
launchSettings.json X 
Properties > { } launchSettings.json > { } profiles > { } dotnet5api 
> 
launch.json 
tasks.json 
bin 
Controllers 
C# WeatherForecastController.cs 
Properties 
o 
launchSettings.json 
o 
o 
C# 
C# 
C# 
appsettings.Development.json 
appsettings.json 
dotnet5api.csproj 
Program.cs 
Startup.cs 
WeatherForecast.cs 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
"$schema": "http://json. schemastore.org/launchsettings. j son" , 
iisSettings" : 
"windowsAuthentication" : 
false, 
anonymousAuthent icat ion" 
true, 
iisExpress" : 
"applicationUrl": "http://localhost:10682" , 
"sslPort": 
44390 
"profiles": 
"IIS Express": 
"commandName": "11SExpress" , 
launchBrowser" : 
true, 
launchUrl": "swagger" , 
"environmentVa riables" : 
"ASPNETCORE ENVIRONMENT " 
": Development" 
"dotnet5api" : 
"commandName": "Project" , 
"dotnetRunMessages": "true" , 
launchBrowser" : 
true, 
launchUrl": "swagger" , 
"applicationUrl": "https://localhost:5Ø01;http://localhost:5Ø00", 
"environmentVa riables" : 
"ASPNETCORE ENVIRONMENT " 
": Development"

Look at the highlighted configuration. 

  1. applicationUrl – It defines the Base URL of the API.
  2. launchUrl – It defines the home page of the API which can be used as a suffix to the Base URL.

You can create as much configurations as you can which makes it really easy to expose the API.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.