Your Guide to Learn ASP.NET Core Web API

With the announcement of .NET 5 and C# 9.0 with their amazing new features and great overall enhancements, the Software development community is getting an increased need and a growing heat to learn and build projects and apps using the latest unified framework. Once of the focus technologies is the ASP.NET Core Web API.

In this article we will mainly focus on a guide for you to learn ASP.NET Core Web API, knowledge in writing solid and secure Web APIs is an essential skill to learn to become a better API developer, so for this I have compiled a list of important topics and concepts with a brief excerpt about each along with useful online resources and other articles on this blog so that you can benefit from and start your learning journey.

I hope this guide will help you learn this amazing framework and become a good ASP.NET Core Web API developer.

Please note that because .NET 5 has been recently announced with final stable release, you will notice that most resources that appear in this compilation might include articles and tutorials related to the previous version of ASP.NET Core 3.1.

But that shouldn’t affect your learning strategy since ASP.NET Core 3.1 is still being supported under Long-Time-Suppprt (LTS) and version 5 is not a lot different than 3.1 in terms of main functions. Follow the link to learn more about the ASP.NET Core 5 Announcement.

Prerequisites

Visual Studio 2019

To be able to start with ASP.NET Core in .NET 5, you need to have the latest version of Visual Studio 2019, update (16.8.1)

If you already have Visual Studio 2019 installed, just head to Help > This update is now available right from Visual Studio Help > Check for Updates.

You can otherwise just download the latest version Visual Studio 2019

Eventually, you should be able to notice the latest version of Visual Studio in the ‘About’ window:

Once you create a new ASP.NET Core project, you should be able to notice the latest version of ASP.NET Core 5

Migrating ASP.NET Core Web API from 3.1 to 5

If you already have a project that is built using ASP.NET Core Web API 3.1 and you want to upgrade it then this is an easy task and won’t require much effort, mainly you will need to change the target framework of your project to .NET 5, update your NuGet packages to the latest version and then verify if all your APIs are still working fine. And if your Web APIs are deployed to IIS, then you just need to install the Windows hosting bundle of .NET Core 5

If you want a tutorial to follow to migrate your project from 3.1 to 5, then you can head directly to my blog post about how to Migrate ASP.NET Core Web API Project from 3.1 to 5

Important Concepts and Topics

HTTP

Hyper-Text Transfer Protocol, is the communication protocol on the web that is used to transmit data such as html, documents, images…etc

It is the foundation of the web, it is important to have a solid understanding of how HTTP works, so check this article for a detailed overview of HTTP

REST and RESTful services

REST Refers to Representational state transfer, which is an architectural style to build Programming Interfaces (APIs) for data manipulation through HTTP

RESTful Services are the web services built using the REST style and are hosted under domain endpoints that allow clients to communicate and access resources

A RESTful Service can support the HTTP Standard Methods (POST, GET, PUT, DELETE and others ) these methods define what the method will do with the underlying resources, so for example a GET method will retrieve resources to the client, POST will save data on the resource.

For further reading, check out it this article

Request Headers

Any HTTP call can include meta-data in the format of string, string dictionary. This represents the request headers collection.

It can include either pre-defined headers such as content-type (request data format), accept (response data format),  authorization (basic {base64} or bearer {token}) and others.

Or you can even introduce custom headers and validate upon them.

HTTP Statuses

HTTP Statuses represent the status of a RESTful service after an HTTP Request has been initiated and completed by the client

The statuses are standardized numerical values

Status CodeStatus Description
1xxRequest received and under processing
2xxSuccessful
3xxRedirection, an action must be taken by either user agent (browser) or user
4xxInvalid Request by the client, might be because of incomplete and invalid data
5xxServer Error

The complete list of HTTP statuses can be found in a numerous locations, check the official Mozilla site

Learn about JSON

JSON is the JavaScript Object Notation, which is a text-based format used to interchange and store data. Its format is easy and simple to understand and parse by humans and machines alike.

Newtonsoft.Json is the most popular NuGet Package for JSON manipulation, with +724 million downloads it is the top downloaded NuGet Package.

It provides super helpful classes, methods, attributes and much more with a blazing fast performance to process and convert your data models to and from JSON Format.

HTTPS

HTTPS is the secure version of http. when a user tries to open a website that data is transmitted through SSL Secure Socket Layer, a website must have a valid SSL certificate applied for the website and installed on the hosting sever for the website to be accessible via the https protocol.

All modern browsers now show a lock icon beside the site that is accessible over https and has a valid SSL certificate.

If you are building an API that accepts personal information or sensitive data like credit cards, you must support only https and not allow plain http calls.

You can check this article to learn How to make your site HTTPS-only

ASP.NET Core Components

Controllers and Routing

Controllers define the HTTP methods and routing urls (endpoints) that will be exposed to the public (clients).

In ASP.NET Core Web API, Controllers inherit from ControllerBase.

The ControllerBase includes many methods and properties to help the API developer handle the HTTP requests/responses. For example there are many methods that wrap your response with a specific type of http status, such as

Under each controller you can define one or more methods to handle a resource related operations.

So for example, you can have a ProductsController and inside it you can have a GET verb that will get all products.

And another GET verb that will get one product by id also another method with a POST verb that will save a product record in your database, such method can sometimes be accessed via admin UI by admin users.

For this case it is important that you implement API security through applying fine-grained role-based authorization policies and requirements so you can provide the proper access to the correct users.

This documentation link has further details about Controllers, Routing and Controller Attributes

Middleware

It is a piece of Software class or component that can be injected somewhere in the pipeline of the ASP.NET Core application to handle or process request/response .

There are predefined middleware within the ASP.NET Core framework, such as UseAuthentication() UseAuthorization();

you can also use a middleware from providers, through NuGet, such as UseSwagger() or UseSwaggerUI(), which are part of Swashbuckle.AspNetCore package which by the way now comes bundled with the ASP.NET Core Web API 5 Template project.

Moreover, you can write your own middleware and inject it into your application’s pipeline, such as ApiKey Authentication Middleware, that can intercept each request to your API that has the [Authorize] attribute decorated with and validate the headers for a valid api-key header.

My article Secure ASP.NET Core Web API using API Key Authentication explains how you can apply API Key authentication using either a custom attribute or middleware.

Attributes

These are decorations that can be applied to classes, methods in order to filter data before or after processing the request to and from the class or the method it is applied to.

In ASP.NET Core Attributes can implement a different number of filters to handle different tasks and also the attributes can be used to provide input for the filters from the controller method.

For more information about attributes in general, you can refer to this blog.

Filters

Filters are used to intercept the processing pipeline, so you can run some code before or after some stage in the process.

One great example for using filter is to handle and log exceptions, you can write a single filter that would do this task instead of having to go through each controller method and adding a try catch block there. This way you can organize your code and avoid redundancy.

Follow this link to learn more about Filters in ASP.NET Core.

Startup.cs

This class includes the initial setup for services and configuration for your whole Web API project. It consists of the Configure method from there you can access the request pipeline and insert the needed middleware and the other method ConfigureServices where you can access the services collection and configure the dependencies so that you can inject them whenever needed throughout your project

Program.cs

This is the entry point to your application, from here your application (before it is even an ASP.NET Core) starts and the only thing happening here is to create webhost using the Startup class

Appsettings.json

This is a JSON formatted file that includes all the settings and configurations that you can use in ASP.NET Core Web API.

This file resides in the server and is mainly useful to control settings on production environment without having to rebuild your code and republish it all over again.

Dependency Injection

You should first understand the dependency injection as a design pattern or a programming concept, before learning how it is used in ASP.NET Core.

Dependency Injection is basically providing an object that is needed by another object, so if a class A depends on class B, then we don’t let class A care about creating an instance of class B itself but inject an instance of class B into A.

This is mainly useful for testing, and for loosely-coupling the dependencies

Check this StackOverflow thread to better understand this topic

Once you get a basic understanding of how and why dependency injection is used, then you can head right away to learn more about dependency injection in ASP.NET Core

API Security ( Authentication and authorization)

ASP.NET Core Identity

The Identity is a framework that introduces membership functionality for the API users, with methods for login, logout, register along with passwords and claims management, and also it define roles and permissions for users. Also it provides UI pages for the membership functionality

The official docs will help you learn more about ASP.NET Core Identity

Basic Authentication

Authorization: Basic YmFzZTY0OmVuY29kZQ==

The basic authentication method is a way to transmit data to the API in a base64-encoded format where the header name is Authorization and the value is ‘Basic’ follow by a space then followed by base64encode(username:password), or base64encode(clientid:secret)

API key Authentication

This is another authentication mechanism mainly used to identify and authorize your API clients (not users), API Key can be passed either via query string, request body, Basic Authentication header or a custom header such as x-api-key

The API will then look for the api key in any of the locations mentioned above and validate it and then authorize the client to access the api.

Check the following tutorial to help you learn how to implement the API Key Authentication in your API Project Secure ASP.NET Core Web API using API Key Authentication

Secure ASP.NET Core Web API Using API Key Authentication

JWT (Json Web Token ) Authentication

JSON Web Token is a way to format your bearer tokens in a standard and simple way, it includes 3 parts: header, payload and signature.

You can build a solid API Authentication with JWT and it is very easily done in ASP.NET Core.

Check this article Secure ASP.NET Core Web API using JWT Authentication

Secure-Web-API-using-JWT-Authentication

OAuth 2.0 and Open Id Connect

OAuth 2.0 is the authentication and authorization standard framework that can guarantee the proper access to the users to your APIs through the different platforms.

You can easily configure ASP.NET Core Web API to implement the OAuth 2.0 framework via identity providers, such as Identity Server 4 , Auth0

You can also enable your users to sign in from their existing credentials on social or external providers

Check this tutorial about Facebook, Google, and external provider authentication in ASP.NET Core

Fine-graining Authorization using Policies, Roles and requirements

You can also check my tutorial Secure ASP.NET Core Web API using JWT Authentication it explains how to apply authorization with a policy and requirement.

API Documentation with Swashbuckle and Swagger

Now in ASP.NET Core Web API 5, OpenAPI is enabled by default once you start a new project with the API template,

Once you create the new ASP.NET Core Web API 5 template project, you can run it and you will start noticing a nice Swagger UI view instead of the regular random JSON result you get on the browser.

This is done through Swashbuckle ASP.NET Core Library.

You can read more about Swashbukle here and how to build help pages using swagger

DTO Data Transfer Objects

It is important that you sepearete the data layer with your API layer, so that you don’t expose the full object details to your clients and have the control on what to display and what to receive from them.

DTOs are plain objects (POCOs) that simply serve as the middle layer between your data layer and your client.

A great transformation tool that comes really handy whenever you have too many database entities and you want to convert them to and from their counterpart DTOs, is the AutoMapper.

With AutoMapper you can define configurations for how to map between your Database entities and DTO classes, and then AutoMapper will handle the rest. And if you are following conventions in naming your DTOs then the mapping will be done without even defining configurations

In ASP.NET Core, it is very easy to integrate with AutoMapper.

Just install the AutoMapper and AutoMapper dependecy Injection extenions NuGet Packages

Create a class that inherits from AutoMapper’s Profile, your class’s constructor will define the mappings between your entities and DTOs

And in Startup class, in configureServices method, configure the AutoMapper with the new class and then append the configurations to the Services Collection Object

In your controller’s constructor, inject the AutoMapper object through the IMapper Interface

Then use the Map method from the injected mapper object to convert between your entity and DTO model.

This SO Answer has a detailed instructions for how to use AutoMapper in ASP.NET Core

Error Handling and Logging

A middleware is the best way to catch all your exceptions, format them and log them. A bad practice is to put a try catch block on each API method.

Check this tutorial to learn how to Handle errors in ASP.NET Core Web APIs

And check this post to understand how to implement Logging in .NET Core and ASP.NET Core

Unifying Error Responses

You should always to try to have a unified structure of error responses to your clients, so that they can identity the error you are trying to transmit.

Once way for this, is that you can create a model that will have a code and description. And then whenever you want to return a 400 BadRequest Response, then you can put your response in an error model object with code and description, so the front-end app or client, once receives the error response, it can easily pick the code and display the proper message for the user ( usually there might be multiple localizations for each code to support multiple languages).

Model State Validation

You can apply data annotations (attributes) to your models so that you can enforce certain backend input validation rules whenever a user is submitting data to your APIs.

These validation rules can include: required property, max number, min number, regex or even more complex rules that you can customize.

Then in your API method, you can simply check if the model state is valid and then return a 400 bad request with the validation message, via the below

If your controller is decorated with the [ApiController] attribute, then you don’t have to specify the above condition since the ApiController does automatically check the ModelState and return 400 BadRequest.

If you want to be able to log the messages that are caused by the ModelState validation when using the ApiController Attribute, then you can refer to this How to log automatic 400 responses on model validation errors

Localization

When building APIs, sometimes you might need to make it support multiple languages/cultures, in this case you have to prepare your APIs to be localized to a specific language and culture.

Follow this tutorial to learn more about localizing your APIs

Entity Framework Core

EF Core is the successor of Entity Framework library used in .NET Framework. You can simply integrate your ASP.NET Core Web API Project with EF Core, and now EF Core is even better with the latest update EF Core 5

To learn more about how to connect your API Project with SQL Server Express DB and Entity Framework Core check my article Build RESTful APIs Using ASP.NET Core and Entity Framework Core

Build RESTful APIs using ASP.NET Core and Entity Framework Core

Hosting and Deployment

IIS Express (Localhost)

This is the first hosting environment you get once you start a new project. Visual studio automatically assigns a random ports, for both http and https, on your local machine’s IIS Express and from there you can start building your APIs and testing them.

launchSettings.json is the file that contains settings that are only related to development and debugging profiles. so it is used only on the development machine and not on the production environment. You can setup multiple profiles for launching url on IIS Express or other local hosting environments.

IIS (On-prem)

If you are willing to host your ASP.NET Core Web API on a Windows Server with IIS, check out my detailed tutorial about how to Deploy ASP.NET Core Web Api on IIS

Deploy Asp.Net Core Web Api on IIS
Deploy to Docker

Docker is amazing platform that provides you the right tools to place all your ASP.NET Core Web API Project along with all its related SDKs and hosting bundle into a container and test your project somewhere else, on a different OS, machine.

You can start from this tutorial

Also read this documentation about how to Dockerize an ASP.NET Core Application

Deploy to Azure

With Azure you can easily take your ASP.NET Core Web APIs to the cloud plus Visual Studio has built-in support for publishing to Azure, so the process is quite simple.

You have multiple options when it comes to deploying your Web APIs to Azure, and the choice would usually depend on the usage and the budget.


Deploy to AWS

Another cloud provider for your ASP.NET Core Web API project is the AWS.

Same as in Azure, based on the expected usage of your APIs and your assigned budget you can choose between different services provided by Amazon to publish your APIs:

Also you can equip Visual Studio with support to publish over multiple AWS services using the AWS extension. You can download it from within Visual Studio. Tools -> Extensions

API Unit Tests

You can create a new test project within the same solution that includes the API project. The test project can be of type NUnit Test or XUnit tests. With a few difference in the structure of both tests, both would give you the ability to writing unit tests for your APIs to test that the controllers, the services, and anything is functioning normally.

You can go through this StackOverflow thread to learn more about the difference between NUnit and XUnit Tests

Always remember to keep your tests to the minimal and to follow the Arrange, Act, Assert order to properly build your tests.

You can also go with the test-driven development methodology (TDD) to start converting the requirements to tests, make them fail and then write the actual functionality to make the tests pass.

Check this article to read more about TDD

Postman for Testing and Simulation

Postman is the ultimate tool to test your ASP.NET Core API endpoints, it has everything you need and more to simulate a client to call your APIs, you can create collections, teams, workspaces, environment variables.

You can download Postman here

Also check this comprehensive tutorial about how to use Postman for testing

Further online resources and learning materials

Extra Resource for Kids

An interesting article about how to help your kids learn Computer Science and coding:

Top 7 Computer Science Basics All Kids Should Learn

Bonus

Mozart is your best pal for studying and focusing on learning new stuff. Please enjoy and happy learning.

Leave a Reply

%d bloggers like this: