Skip to content

ASP.NET Core Series 01: Building RESTful API with Dapper and Deploy to Azure App Services

Hi, guys.

Actually, I was thinking about writing some articles about ASP.NET Core, but I couldn’t find enough time. These days, I’m working on ASP.NET Core for certain uses, for example how to easily do dockerizing. Therefore, I will write some articles on ASP.NET Core.

In this article, we will build a lightweight RESTful API with ASP.NET Core. We will use Dapper and the Repository pattern for data operations and we will handle global exceptions with Serilog. At the end of the development, we will add Swagger UI, and then deploy the project to Azure App Services.

Creating Project Structure

Firstly, we will create an ASP.NET Core Web API project using PowerShell commands. Let’s create a new folder called  “aspnetcore-rest-api-with-dapper“, then we can create an ASP.NET Core Web API project with using the “dotnet new webapi” command as shown below.

Now, we have to open the project in Visual Studio Code with using “code .” command. After that, the project template will open in Visual Studio Code.

Now, let’s start some coding!

Model Declaration

Let’s assume we are developing an e-commerce website and we need a RESTful API to manage our product resources. Let’s create a “Models” folder in the project and add a new class called “Product“.

created SQL script looks like:

Contract Declaration

First, we will declare Request and Response objects. Let’s create a new folder called “Contracts” then add a “ProductRequest” class inside the “Contracts” folder as shown below.

Now, add a “ProductResponse” class.

We will use the “Message” property to give information to clients when requested products not found. If the “Message” property is null, it will be ignored when returning a response to clients.

Create a Controller

So far, we created common objects. Now we can start coding and implementation in the following order: “Controller > Business > Data“. First we need to create a “ProductsController” class inside “Controllers” folder, and code as shown below.

We injected “IProductBusiness” interface from the constructor then used the “GetAsync“, “GetAllAsync” and “AddAsync” methods in the controller. At this point, we have to be careful to be task-based to gain a little performance to the system.

Also, we defined the URL path as “api/v1/products“. This operation is important for version management.

Building Business

We used “IProductBusiness” interface while we were coding the controller. Now, let’s create a “Business” folder and add an interface called “IProductBusiness“.

We can implement now “IProductBusiness” interface as shown below:

This time, we injected the “IProductRepository” from the constructor and used the “GetAsync“, “GetAllAsync” and “AddAsync” methods.

NOTE: We did not apply pagination operation in “GetAllAsync” method. You should not forget to apply that. 🙂

Data Access Operations

We will use the Repository pattern and Dapper here to supporting data operations. Therefore we have to include Dapper to the project, brought over from NuGet as like below.

After including Dapper from NuGet, we will create a new folder called “Data“, and let’s define “IProductRepository” interface inside that as shown below.

Here, we will just define some methods. These are the “GetAsync“, “GetAllAsync” and “AddAsync” methods. Let’s add a “ProductRepository” class then implement the “IProductRepository” interface.

If you look at the above code block, you can see that we just used Dapper’ async methods. Now we have completed theController“, “Business” and “Data” operations.

Global Exception Handling with Serilog

There are a few ways to manage exception handling in ASP.NET Core. We can choose middleware or MVC exception filters. At this point, I prefer to handle exceptions in middleware, because I saw a tip in Microsoft’s documentation: MVC exception filters are not as flexible as error handling middleware.

Firstly, we have to include Serilog’s file logger to the project from NuGet as shown below.

After this, create a new folder called “Middlewares” and add a “GlobalExceptionMiddleware” class inside the “Middlewares” folder.

We handled exceptions in middleware in a straightforward way. Now, we should do two things. On the one hand, we have to add a “GlobalExceptionMiddleware” class to ASP.NET Core middleware in “Startup.cs” and on the other hand we have to define a log file path.

Swagger Implementation

Swagger is a really great tool, especially for developers when using API. Let’s add Swagger to the project from the NuGet server as shown below.

Now, we have to enable Swagger in “Startup.cs“.

That’s all. If you run the project, you can reach the Swagger UI on “http://localhost:5000/swagger” URL.

Injection of Application Services

We used “IProductBusiness” and “IProductRepository” interfaces at the beginning of this article. Now, we have to define concrete classes in “Startup.cs” to injection operations.

As follows:

We are completely ready!

Let’s build the project with using the “dotnet build” command on the terminal, and after that, we will run the project with the using the “dotnet run” command. Now, we can reach the Swagger from “http://localhost:5000/swagger” URL.

Deploy to Azure App Services

Firstly, we have to do the following steps in the Azure Portal:

  1. Log in to the Azure Portal.
  2. Click “New” button at the top left of the Portal.
  3. Select “Web + Mobile > Web App” section as shown below from the drop-down menu.
  4. If you have not any subscription, you have to click “Sign up for a new subscription“, then you can get a one-month free subscription.
  5. We have to specify “App name” field uniquely. I specified “AspNetCoreRestfulApiSampleGokhanGokalp” as “App name“, and then click to create. (this operation could take little times)
  6. After clicked to create, we will get a notification something like “Deployments succeeded” as shown below:
  7. Now let’s open “Deployment options” section at the top left of the Menu, then click to “Local Git Repository“.
  8. And now, we have to specify “Deployment user name” and “Password” fields for basic authentication operation.
  9. We can get the “GIT URL” now. Open “Settings > Properties” section at the left of the Menu.

We are ready for publishing the project to Azure App Service. We need to create a local Git repository in Visual Studio Code. Open “Source Control” section at the left of the Menu, then click to “Initialize git repository” button.

After that, click the “Commit All” check icon. Let’s create a remote reference for pushing updates to the web app with using the following command.

Now we have to run the following command, so the credential information can be added automatically in push operations.

We need to push the changes to Azure with the following command:

When operations are finished, we can see a few line commands as shown below:

That’s it. Now, we can reach the project from here “http://aspnetcorerestfulapisamplegokhangokalp.azurewebsites.net/swagger/“.

I hope this article would help who needs any information about building ASP.NET Core RESTful API with some awesome 3rd libraries. Currently, I’m working on the ASP.NET Core for the Linux platform. See you in the next ASP.NET Core article series.

https://github.com/GokGokalp/aspnetcore-rest-api-with-dapper

Some references:

https://github.com/Microsoft/azure-docs/blob/master/articles/app-service-web/web-sites-create-web-app-using-vscode.md

https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger

Bu makale toplam (12656) kez okunmuştur.

48
1



Published inASP.NET CoreAzure

15 Comments

  1. ahmet ahmet

    Hocam şu ProdcutResponse oluşturulurken
    public ProductResponse()
    {
    Products = new List();
    }

    ve

    public List Products { get; set; }

    kısımlarında List’ler kızarıyor sebebi nedir?

    • Merhaba, kodları şekillendirmek için kullandığım plugin den kaynaklı sanırım type’lar gitmiş. 🙁 Farketmemiştim. Düzelteceğim, teşekkürler.

      “public List Products” şeklinde olacaktı.

  2. ahmet ahmet

    Hocam peki dapper referance nasıl ekleyeceğiz arama kısmına yazdığımda bulamadım

    • Merhaba, “dotnet add package Dapper” komutunu çalıştırıp, ardından “dotnet restore” yapmanız gerekmektedir.

  3. ahmet ahmet

    her şey iyi hoş lakin neyi neden yaptığımızı hiç anlamadım keşke yeni başlayanların da anlayabileceği bir dilden anlatsaydınız

    • Yazdığım bazı makaleler, genelde bu teknolojileri .NET Framework’de kullanan kitleye hitap etmektedir. Amacı ise başlığında olduğu gibidir aslında. Dapper kullanarak RESTful bir API tasarlama ve biraz da Azure App Servis’i göstermek. Yorumun için teşekkürler.

  4. ahmet ahmet

    Hocam merhaba,
    Since ‘ProductsController.Get()’ is an async method that returns ‘Task’, a return keyword must not be followed by an object expression. Did you intend to return ‘Task’? [aspnetcore-rest-api-with-dapper]
    şeklinde bir hata alıyorum çözümü nedir acaba?

  5. ahmet ahmet

    Hocam biraz çaba sarfettikten sonra daha da iyi oturdu her şey. Teşekkürler ekstradan verdiğiniz cevaplar için 🙂

  6. son son

    DI için Autofac imi tercih edersiniz yoksa .net core la gelen DI yımı.

    • Merhaba, genelde benim tercihim .NET Core içerisinde build-in olarak gelen DI’ı kullanmak. Bazı makalelerde ise autofac gibi library’lerin dependency load işlemlerinin bir tık daha hızlı olduğu söyleniyor, ama ne derecede ne farkeder bilemiyorum. 🙂

  7. Can Can

    Merhaba, test işlemlerini yaptığımda Post metodu olumlu yanıt veriyor fakat tabloya veriyi eklemiyor. Sebebini anlayamadım. Post etmeye çalıştıgım veri aşağıdaki gibi. Olası nedenleri ne dir?

    {
    “CategoryId”:”5″,
    “Name”: “Seker”,
    “Description”: “Tatli”,
    “Price”:”250″
    }

    • Merhaba, kusura bakmayın geç cevap için.

      Create için ilgili örneği boş bıraktığım için geriye herhangi bir status code dönmediği için olumlu yanıt veriyordur. Debug ettiğinizde gönderdiğiniz parametreler ProductRequest e bind oluyor mu? Bir diğeride ProductRepository içerisindeki AddAsync method’undaki query’den [Id] kısmını çıkartıp bir deneyebilir misiniz?

      Teşekkürler.

  8. Dapper için güzel bir kaynak oldu çok teşekkürler. Performans için oldukça önemli bir ORM aracı haline geldi Dapper. Türkiye’dede kullanımı daha da yaygınlacak.

Leave a Reply

Your email address will not be published. Required fields are marked *

*