Create .Net Core Web API

Bugra Sitemkar
7 min readNov 17, 2019

This story is second part of series Creating a Url Shortener Service From Scratch with .Net Core series. In this part we will create a .Net Core 3.0 Web API application for the server side.

If you are not familiar with HTTP protocol, and REST architectural style or need a quick refresher, please read the following articles first.

Web API HTTP Basics

Web API Rest

Also the generally accepted design principles are considered when designing this API.

Prequisites

Install .Net Core 3.0 SDK if you do not have it.

Install Visual Studio 2019 as I find it more convenient for .NET Projects rather than VS Code.

Creating a Mongo Db Cloud Atlas cluster before starting the project will be handy. You can also create at the final step.

Create Solution and API Project

From the Visual Studio 2019 Splash Screen, select Create a New Project option. Select ASP.NET Core Web Application C#, click Next.

Enter Project Name: ShortUrl.API

Solution Name: ShortUrl

Click Create. In the next screen Select ASP.NET Core 3.0 and API. Click Create.

Delete WeatherForecastController under Controllers folder, and WeatherForecast.cs class file.

Although actual development is more back and forth process, and not as straight forward as this tutorial is going to be, I will go through each project in solution one by one for the sake of simplicity.

Create Model Project

Let’s create model project which we will be using across all other projects. Right click on ShortUrl Solution, Add, New Project. Select Class Library (.NET Standart) and name is as “Model”.

We need to include MongoDB.Bson library in this project as we are going to add Base model and DTO model to this project and add Mongo DB properties. Type the following command to Package Manager Console. Please be sure you have selected “Model” project on the Default Project dropdown of Package Manager Console.

Install-Package MongoDB.Bson -Version 2.9.3

Before adding models, we need a custom validation attribute to check the url send.

Right click on model, select “Add Folder”, name the new folder as Validation. Right click on validation folder and add a new class file named as “CustomValidation.cs”. In custom validation class, we are accepting full urls as valid (either http or https).

Finally two entity models to use with Mongo Db, a request and a response model.

File Structure of Model project is as follows:

— Model Project

— —Validation Folder

— — — CustomValidation.cs

— —MongoBaseModel.cs

— —ShortURLModel.cs

— — ShortURLRequestModel.cs

— — ShortUrlResponseModel.cs

Create Repository Project

We are going to move developing the project from repository to service to API finally. Create a Repository project in the same fashion as Model project under ShortUrl solution.

Before adding any class, first include the dependencies for the repository project.

From the package manager, select Repository project as default project and execute the following command to include MongoDb driver package.

Install-Package MongoDB.Driver.Core -Version 2.9.3

Also right click on Dependencies, Click Add Reference, from the projects, select Model project and add as dependency.

After the dependencies are added, first add an Abstract folder under Repository project. This folder is going to contain our interface for ShortUrl repository. This IRepository, interface is going to contain necessary methods we will be using through our service.

Then we can include a generic repository for MongoDb and inherit from this generic repository to produce more specialized repositories for task needed. I have named generic repository as MongoRepository.

Finally we are going to add a specialized Repository, I name it as ShortUrlRepository. This class inherits from MongoRepository and implements IRepository interface.

Here is the file structure for repository project:

— Repository Project (.NET Core Class Library)

—— Abstract

— — — IRepository.cs

— — MongoRepository.cs

— — ShortUrlRepository.cs

Create Service Project

Next, create a service layer. Controller layer should only receive the request, call the service and return the response as its single responsibility. Service layer will be used for mapping Request/Response models to DTO’s and back as well as any business we need to implement.

Before adding classes, include models and repository projects as dependency just like we did in repository project.

Create another class library project same as Repository project. Name it Service. Create Abstract, Map, and Utilities folders in the project. The file structure going to be as follows:

— Service Project (.NET Core Class Library)

—— Abstract

— —— IShortUrlService.cs

— — Map

— — — ShortUrlModelMapper.cs

— — Utilities

— — — TokenGenerator.cs

— — ShortUrlService.cs

The Short Url Service Interface, contains necessary service methods.

Add token generator under utilities folder, which will generate short url tokens.

Then add Short Url Model Mapper class handles the mapping operation and generates short url from token generator while mapping request model to dto model.

Finally let’s add Service class.

API Project

Now we have our model, repository and service projects are ready, we continue implementing the API project.

Add Dependencies

First let’s add necessary Nuget Packages.

In the Package Manager Console tab, Paste following commands.

This package is for easy API versioning:

Install-Package Microsoft.AspNetCore.Mvc.Versioning -Version 4.0.0

This package is for logging:

Install-Package NLog.Web -Version 4.9.0

Include all three Model, Service, and Repository projects as dependencies.

Create Controller

Right click on controller folder, Add, Controller. Select API Controller — Empty. Name it as ShortUrlController.

Redirecting or returning the short url model !

If you notice, the Get method takes a redirect parameter from query string, which has default value set as true. If redirect query parameter is not send or send as true, the method redirects to the original url found using short url, and if redirect method is false, Get method returns the model with found short url and does not redirect. Overloading a method in this manner may not be the best practice in a real production environment. I did this way, for the sake of simplicity but normally you should create another controller to handle redirect functionality.

Versioning the controller

I like Url versioning, found it more readable and understandable.

[ApiVersion(“1”)] indicates the version of this controller.

[Route(“api/v{version:apiVersion}/[controller]”)] enables us to inject ApiVersion property above to controller route such as api/v1/shorturl in this example.

Logging

We are defining logger (ILogger<ShortUrlController> logger) and injecting the logging interface which enables us to use any logging solution. We are using NLog in this project.

Right click on ShortUrl.API project, Select Add, New Item. Search for config in the search box top right. Select Web Configuration File and name it as “nlog.config”. We will be using this file to configure logging.

One last step is necessary to enable logging with NLog, change the Program.cs class as follows which sets the NLog as the default logging provider to this application with a log level of trace.

Adding Services to Container / Configuring request Pipeline

The middlewares can be added directly under ConfigureServices and request pipeline can be configured directly under Configure method in the Startup.cs file. I like creating Extension methods and calling them from ConfigureServices and Configure methods more.

Let’s create an Extensions folder under ShortUrl.API project.

Global Error Handling

Implementing a global error handling is very userful. The following extension method is going to return 500 HTTP status code with the exception message in case of any unhandled exception occurs within the project.

Create Error Model class under Extension directory. Then create a Configure Extension class.

We will be calling this method later from Startup.cs class.

Configuring Cors and Registering Service and Repository classes.

We need to configure Cross Origin access to not to limit API requests to a single origin. If you decide to not to give access to this API openly but to consume from just a frontend application, you need to configure Cross Origin access accordingly. We will talk about it later when building frontend application so you do not need to worry about that now.

Also registering Repository and Service classes for injection in this Extension too.

Create a class named ServiceExtensions under Extensions folder and add following methods.

We will have to call this methods from Startup.cs too.

Finally, call the middlewares from Startup class.

Notice we are also adding API Versioning as a service in the ConfigureServices method (services.AddApiVersioning()).

Adding Development Settings

Add the connection string from connect to short-url section of your created mongo db cloud cluster to appsettings.Development.json

If you do not already created a free Mongo Db Cloud Atlas cluster, follow the link to create one.

Adding Production Settings

I recommend always adding a Production settings file in order to keep environmental configuration separate.

Right click on ShortURL.API project, select Add, New Item. Search for appsettings in the right top search box. Select App Settings File and name it as appsettings.Production.json. Visual studio is going to automatically add Connection String and Logging sections. We are going to edit this file prior to deploying API to production.

We have created the backend application with following features;

  • Core functionality: Creating a short url link from a url, retrieving previously created short url link from a url, redirecting to a url using created short url.
  • API Versioning
  • Logging with NLog
  • Global Exception Handling

I omit API documentation with swagger or hateoas links intentionally to keep the project simpler. Please keep in mind, API documentation is one of the necessary steps to develop a proper API.

Next Step

We will dockerize this application in the next step to make ready to deploy to Digital Ocean VPS.

--

--

Bugra Sitemkar

Software Engineer | .NET Enthusiast | Writer. Diving deep into software craftsmanship. 🚀