Creating a REST Web API in C# with ASP.NET Core 5.0 and Visual Studio Code

Luis Hernandez
10 min readMay 2, 2021

--

Step-by-step guide to show you how to create a REST Web API in C# with ASP.NET Core 5.0 and Visual Studio Code. And how test it using either Swagger or a REST Client extension.

Photo by James Harrison on Unsplash

This article is a step-by-step guide to show you:

  • How to create a REST Web API in C# with ASP.NET Core 5.0 using the dotnet CLI (Command Line Interface).
  • How to add CRUD (Create, Retrieve, Update, Delete) methods to our REST Web API in C# using Visual Studio Code.
  • How to test the Web API using either Swagger (in the Browser) or a REST Client extension (in Visual Studio Code).

Prerequisites

  1. First you need to check if you have installed the .NET Core 5.0 SDK with the following .NET CLI (Command-Line Interface) command:
dotnet --version

If your version is not 5 or above, download the .NET Core 5.0 SDK and install it on your machine.

2. Install Visual Studio Code editor (also know as VSCode).

3. Once Visual Studio Code is open, install the REST Client extension.

4. Finally, install the C# extension to get IntelliSense features in VSCode.

Creating an ASP.NET Core 5.0 Web API Project

Now let’s create a Web API project with a few endpoints that will allow you to manage a list of Superheroes, with the typical CRUD (Create, Retrieve, Update, Delete) operations. In order to scaffold this project, type the following command:

dotnet new webapi -o Superhero

This creates a folder named Superhero with the ASP.NET project using the webapi template.

Running the Sample Project

Open the Superhero folder in Visual Studio Code. Then open a new Terminal from the Terminal menu and launch the sample application by typing:

dotnet watch run

This will launch Swagger UI in your browser with the sample Web API as shown in the below image. Click on Try it out and you will see the Response from the sample Web API application that comes with the webapi project template:

If your browser complaints about the certificate, in Windows you can trust it using this command:

dotnet dev-certs https --trust

To trust the HTTPS development certificate included in the .NET SDK in other operating system. Please take a look at the official documentation.

To test the Web API withind Visual Studio Code, create the test.httpfile in theSuperherofolder’s root and paste this content:

GET https://localhost:5001/weatherforecast

And click on Send Request(as shown in the below image) to see the Response displayed in the right side:

In the previous image you can see a collection of files and folders scaffolded by .NET CLI. The Program.cs file contains the starting point of the application. Its content looks like the following:

The static Main() method is automatically called when the application starts. It creates a default web host using the startup configuration, exposing the application via HTTP through a specific port (by default, port 5000 for HTTP and 5001 for HTTPS).

As you can see, the webBuilder.UseStartup() method refers to the Startup type. This type is defined by the Startup class in the Startup.cs file. The default content of this file is shown below:

The Startup class allows you to set up services for the current application. In particular, it allows you to register services via the ConfigureServices() method and to configure the HTTP request pipeline via the Configure() method. In the body of the latter method, you find a few statements that declare the middleware to use.

The rest of the application code is located in the WeatherForecast.cs and WeatherForecastController.cs files. These files implement respectively the model and the Web APIs controller for the sample application coming with the .NET template.

Creating a CRUD API

To get started, remove the WeatherForecast.cs file from the root of the project and the WeatherForecastController.cs file from the Controllers folder.

Creating the model

As a first step, create the model for the Superhero Web API. It will be the representation of the resource that will be exposed to the clients. In particular, it will be implemented as a class representing the single Superhero item. So, add a file named SuperheroItem.cs in the root folder of the project and put the following content in it:

Creating the controller

Now, you need to create the API controller to handle HTTP requests. Create the SuperheroController.cs in the Controllers folder and put the following code inside it:

A controller in ASP.NET is a class inheriting from ControllerBase. The base class provides properties and methods that are useful for handling HTTP requests, as you will see later on.

At this stage, the SuperheroController class simply defines the static variable Superheroes as a small list of Superhero items. In a real-world scenario, the Superhero items should be persisted into a database, but to keep things simple, your application will rely on this volatile solution.

The class is decorated with two attributes: ApiController and Route.

The ApiController attribute enables a few handy behaviors, like the automatic HTTP 400 responses when the model is in error, the automatic binding of URL parameters to method parameters, and similar.

The Route attribute allows you to map a URL pattern to the controller. In this specific case, you are mapping the api/[controller] URL pattern to the controller. At runtime, the [controller] placeholder is replaced by the controller class name without the Controller suffix. That means that the SuperheroController will be mapped to the api/superhero URL, and this will be the base URL for all the actions implemented by the controller. The Route attribute can be also applied to the methods of the controller, as you will see.

Getting a list of items

Once you have the basic infrastructure for your controller, you need to add an action to it. An action is a public method of a controller mapped to an HTTP verb. So, add a new method to the SuperheroController class as shown in the following:

The method Get() allows the client to get the whole list of Superhero items. It is decorated with the HttpGet attribute which maps the method to HTTP GET requests sent to the api/superhero URL.

The return type of the method is ActionResult<List<SuperheroItem>>. This means that the method will return a List<SuperheroItem> type object or an object deriving from ActionResult type. The ActionResult type represents the HTTP status codes to be returned as a response. As said before, the ControllerBase class provides a few features to deal with HTTP requests. Some of these features are methods that create HTTP status code in a readable way, like Ok(), NotFound(), BadRequest(), and so on. The Ok(Superheroes) value returned by the Get() method represents the 200 OK HTTP status code with the representation of the Superheroes variable as the body of the response.

Note: An ASP.NET action may return different types: a specific type, IActionResult, or ActionResult<T>. Each return type has pros and cons. See the documentation for more information.

To test this first action implementation, run the application by typing the following command in a terminal window:

dotnet watch run

Note: If you are already running your web app, stop it using Ctrl + C, and run it again.

Check the response in Swagger:

In Visual Studio Code paste the following content into the test.http file and click on Send Request:

### Get All
GET https://localhost:5001/api/superhero

You will see the response in the right panel:

Getting a single item

The next action you are going to create will allow your client to get a single Superhero item. The action will expect a term as input and will provide an instance of SuperheroItem as a result.

Add a new method definition to the controller class after the previous action definition, as in the following:

As you can see, you have an overloaded definition of the Get() method mapped again to the HTTP GET verb. However, in this case, you have a Route attribute for the action. This attribute appends a new variable element to the URL of the action. So, this action will respond to the HTTP request sent to the URL pattern api/superhero/{id}. The {id} part of the pattern can be replaced by any non-empty integer and its value will be mapped to the Id parameter.

This method checks if the requested id exists in the Superheroes list and returns the Superhero item. It the id doesn't exist, it returns a 404 Not Found HTTP status code.

Now, let’s test this action:

Creating an item

Going ahead with the CRUD operations implementation, you need to allow the client to add a new Superhero. Append the followingPost() method to the controller class:

In this case, the action is mapped to the HTTP POST verb via the HttpPost attribute. The Post() method has also a superheroItem parameter whose value comes from the body of the HTTP POST request. Here, the method checks if the term to be created already exists. If it is so, a 409 Conflict HTTP status code will be returned. Otherwise, the new item is appended to the Superheroes list. By following the REST guidelines, the action returns a 201 Created HTTP status code. The response includes the newly created item in the body and its URL in the Location HTTP header.

Run again the application and add a new Superhero item by adding the following into test.http file (make sure you have blank line after Content-Type):

### Create one
POST https://localhost:5001/api/superhero
Content-Type: application/json
{
"id": 4,
"name": "Flash"
}

Click on Send Request and you should get a long output similar to the following:

Notice the 201 Created HTTP status code, the value /api/superhero/4 for the Location header and the content of the response body. This is what you said to return at the end of the action execution.

To verify that the new item has been actually added to the Superheroes, execute again the first request. You should get the newly added item.

Note: Be sure to not stop the application between the item addition and the item existence check. Remember that the Superheroes list is implemented as a static variable, so, when the application stops, you lose any changes.

Updating an item

After adding an item, allow the client of your Web API to update it by appending the Put() method to the controller class, as shown below:

The Put() method is decorated with the HttpPut attribute that maps it to the HTTP PUT verb. In short, it checks if the Superhero item to be updated exists in the Superheroes list. If the item doesn't exist, it returns a 400 Bad Request HTTP status code. Otherwise, it updates the item's definition and returns a 200 OK HTTP status code.

Test this new action by adding the following:

### Update
PUT https://localhost:5001/api/superhero
Content-Type: application/json
{
"id": 4,
"name": "Aquaman"
}

To verify that the existing item has been actually updated, execute again the first request. You should get the updated item.

Deleting an item

Finally, you implement the deletion of an item from the Superheros list by appending the Delete() method to the controller class:

The HttpDelete attribute maps the method Delete() to the DELETE HTTP verb. The Route attribute appends a new element to the URL the same way you learned when implemented the action that gets a single Superhero item. So, when a DELETE HTTP request hits the api/superhero/{Id} URL pattern, the method checks if the item exists in the Superheroes list. If it doesn't exist, a 404 Not Found HTTP status code is returned. Otherwise, the Delete() method removes the item from the Superheroes list and returns a 204 No Content HTTP status code.

After you had added this code, test this new action by adding the following:

### Delete one
DELETE https://localhost:5001/api/superhero/3

Check that the Superhero item no longer exists in the Superheroes, by executing a Get request with that Id.

You should get a 404 Not Found response similar to the following:

You can check that the other Superhero items still exist by getting all the items with the Request you already know.

You should get all the Superhero items but the one related to Id number 3:

Well, I hope you have enjoyed this article. As you can see, ASP.NET Core 5.0 in conjunction with Visual Studio Code, are very good free alternatives for creating a REST Web API. Also, notice that with ASP.NET Core 5.0 you can build platform-independent and lightweight applications.

Happy coding!

Note: This article has been based on this article: Building and Securing Web APIs with ASP.NET Core 3.0

--

--