ASP.NET Core 6: Creating API for CRUD Operations using EntityFrameworkCore (Basic for new ASP.NET Core Learners): Part 1

In this article, we will go through the steps for creating ASP.NET Core API. We use API aka REST 

APIs for creating data communication services. In short, we can say that we are building a service that can be consumed (or subscribed to) by any client application e.g.  JAVA, .NET, JavaScript Clients (like React, Angular, and Vue.js) so that these applications can make HTTP Requests and perform Data communication in JSON form. We can say the APIs can establish a data communication bridge between homogeneous or heterogeneous applications.   

The ASP.NET Core is a complete eco-system that provides a single HTTP Pipeline for the following applications

  • ASP.NET Core Razor Application
  • ASP.NET Core MVC Application
  • ASP.NET Core  Web API Application

In this step-by-step post, we will use Visual Studio 2022 for creating the ASP.NET Core API project and SQL Server 2018 for the database. 

The database scripts are provided in Listing 1.


Create Database Company
GO

CREATE TABLE [dbo].[Department](
	[DeptNo] [int] NOT NULL,
	[DeptName] [varchar](100) NOT NULL,
	[Capacity] [int] NOT NULL,
	[Location] [varchar](100) NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[DeptNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
	ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, 
    OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[Employee](
	[EmpNo] [int] NOT NULL,
	[EmpName] [varchar](200) NOT NULL,
	[Designation] [varchar](200) NOT NULL,
	[Salary] [int] NOT NULL,
	[DeptNo] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[EmpNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, 
OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

Listing 1: Database Scripts

Step 1: Open Visual Studio and create a new ASP.NET Core Web API project as shown in Figure 1



Figure 1: ASP.NET Core Web API Project

On this window, click on the Next button, here we need to enter the Project Name, and the location where the project will be stored. By default, the Solution Name is the same as the project name. Set the project name as Core_EFApi as shown in Figure 2



Figure 2: Setting the Project Name

On this window click on the Next button. The next window is the most important one. On this window, we need to select the Target Framework for the application. Here we will be selecting .NET 6 (.NET 7 is already out, you can select it as well). The next setting is the Authentication Type. These are the access security settings for our Web API. There are options available as None, Microsoft Identity Platform, and Windows. We will be selecting None as the Authentication Type. Then there are checkboxes provided where we need to Configure HTTPS access to the Web API (this is by default checked so keep it as it is). There is a check available for Docker support (keep it unchecked. The docker is out of scope for this article.). We have further checkboxes for the use of controllers in our Web API project. Keep this checked because we will be using Controllers classes for Web API creation. Also, keep the rest of the defaults on this window as it is as shown in Figure 3



Figure 3: Project creation settings

Click on the Create button. We have created a Web API project. The project structure is shown in Figure 4


      

Figure 4: ASP.NET Core Web API Project structure

In this project, we have the following important files and folder

  • appsettings.json
    • This file contains all application-level settings e.g. Connections string to the database, Loggine, etc.
    • This is a JSON file and all settings in this file are provided using the Key: Value pair. 
    • Our API project reads settings from this file programmatically, which we will see in Part 2 of this post.    
  • Program.cs
    • This is an entry point for the project.
    • This file is responsible for following
      • Hosting 
      • Services registration
      • HTTP Pipeline configuration using the Middlewares
    • Running the application so that it can be requested  
  • Controllers folder
    • This folder contains all controller classes.
    • These controllers contain the action methods that are accessed using HTTP requests for performing Read/Write Operations.

Step 2: Now we have created a Web API project. Open the appsettings.json file, this file contains some default settings for Logging, AllowedHosts, etc. We will modify this file by adding settings like database connection string in forthcoming steps. Open Program.cs file. This file contains some code by default as shown in Listing 2

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();


Listing 2: Program.cs  

Have a careful look at the code in Listing 2. The WebApplication class is used here that is used to configure HTTP Pipeline for handling the HTTP requests using routes. The CreateBuilder() method of this class returns an instance of WebApplicationBuilder class. This class has pre-configured defaults for the ASP.NET Core applications. The WebApplicationBuilder class contains the following important properties:

  • Configuration
    • This provides a collection of configuration providers. These are handled using the ConfigurationManager class. The WebApplicationBuilder class has the Configuration property of the type ConfigurationManager. This property is used to read JSON keys from appsettings.json file.  
  • Environment
    • The Environment property of the type IWebHostEnvironment provides information about the web hosting environment where our application is running.  
  • Host
    • The property Host of the type ConfigureHostBuilder is used for configuring host-specific properties.  
  • Logging
    • The property Logging of the type ILoggingBuilder is used to configure a collection of logging providers for the application.
  • Services
    • The property Services of the type IServiceCollection is used to configure services for the application.
    • These services are the various framework-provided services like Data Access, Authentication,  Authorization, CORS, Identity configuration, Caching, Sessions, custom services, and many more.
    • The ASP.NET Core provides a default Dependency Container for registering and managing dependencies. So that all application dependencies can be registered in the container managed by IServiceCollection using the IServiceProvider interface.
    • The IServiceCollection interface implements the ICollection interface of the type ServiceDescriptor. This class is actually responsible to describe service types that are registered in the dependency container along with their lifetime. 
    • The service life can be Singleton, Scopped, or Transient.      
  • WebHost
    • The WebHost property of the type ConfigureWebHostBuilder is used for configuring server-specific properties.
    • This property is actually responsible for
      • The Kestral server configuration
      • Setting the content root for executable files, the compiled assemblies e.g. the .dll, and the content files like razor files.
      • Logging configuration
      • Services configurations
The Program.cs have already added services for API Controllers using the AddControllers() method as well as services for Swagger for accessing APIs with its UI page. We will add other custom services in forthcoming parts of this post.

The Program.cs, there is call to the Build() method of the WebApplicationBuilder class. This is where the HTTP Request pipeline configuration started with Middlewares registration in it. The Middleware is an important concept of ASP.NET Core. Using the middlewares we can decide various objects used during HTTP Request processing e.g. Excepions, Authentication, Authorizations, StaticFiles, Routing, etc. One of the important middleware is UseHttpsRedirection(), this middleware is used to map the HTTP request to HTTPS request.

The Run() method will start running the application and start listeneing for the incomming requests. In the project we have WeatherForecaseController class.

The Figure 5 shows some of the services and the Middlewares used in ASP.NET Core Applications





Figure 5: The Services and Middlewares

This is API controller class that is derived from the ControllerBase class.  The ControllerBase is an abstract class. This class contains properties and method for executing received HTTP requets and generates response with result. The HttpContext is one of the most important properties of the ControllerBase class. This property is of the type HttpContext. The HttpContext class provides encapsulation over HTTP-specific information about the current HTTP request like User, Session, etc. 

The actual middleware execution uses the HttpContext class extensively to load the middleware object in current HTTP request. The ModelState property of the ControllerBase is used when you want to validate the data received by the HTTP POST and PUT request. 

The RouteData property of teh ControllerBase class is used to monitor the current route expression e.g. Controller Name and the Route parameter that is passed in the URL. 

Each method of the ControllerBase class return a type of IActionResult interface. This is the contract that represent the response data generated after controller executes the request. There are several method availabe in the ControllerBase class e.g. Ok(), NoContent(), Conflict(), BadRequest(), etc. All these method represents response generated after the action method of the controller class. 

If you see the code of the WeatherForecaseController class, the class is  applied with the Route attribute. This attribute has the '[controller]' template. This means that it is a Controller class name excluding the 'Controller' word from the Controller class name. E.g. for the WeatherForecaseController class the route expression will be as follows

https://servername/WeatherForecast

If we want and if our applicatio  needs we can change the Route Template  as follows

[Route('api/[controller]/[action]')

This  means that the HTTP Request url will contain the startc word as api, then controller class name and then action method name in the controller class. Here the question is what is action method? The simple answer is, it is the method in controller class that can be requested using the HTTP request. In the WeatherForecastController class, the Get() is an action method. This is decorated with [HttpGet] attribute. This means that, this action method will be accessed using HTTP GET request. Likewiase, we have HttpPost, HttpPut, and HttpDelete attribute for HTTP POST, PUT,a nd DELETE request respectively.

Now since, we have seen the Project structure, lets run this project. Since the project already uses swagger service and middleware, we will see the Swagger test page once the app runs as shown in Figure 6



Figure 6: The Swagger Page       
     
We will slao see the Command window that show the Application Hosting port for http and https redirection as shown in Figure 7



Figure 7: The Command Window               
 
Here we can see that the app is hosted on Http and Https port. We can access this application from both ports. You can now test the  WeatherForecaseController by clicking on Get button and then on Try it out button  and then on  Execute button to test the HTTP GET request, the Get method of the WeatherForecaseController will be executed and will respond the JSON data as shown in Figure 8.



Figure 8: The Get request

So we have our default code ready. This is the first step towards learning the Web API in ASP.NET Core. In the Part 2 we will see how to use EntityFrameworkCore to build the Data Access Layer.          

       


Popular posts from this blog

Uploading Excel File to ASP.NET Core 6 application to save data from Excel to SQL Server Database

ASP.NET Core 6: Downloading Files from the Server

ASP.NET Core 6: Using Entity Framework Core with Oracle Database with Code-First Approach