Create A REST Web API In ASP.NET Core 3.1 - ASP.NET Core CRUD Web API

Sameer Saini April 06, 2022
Create A REST Web API In ASP.NET Core 3.1 - ASP.NET Core CRUD Web API

In this blog post, we will create an ASP.NET Core Web API from scratch step by step. 

We will follow RESTful principles and create CRUD operations and create an ASP.NET Core Web API in .NET Core version 3.1.

During the implementation, we install and use Entity Framework Core to connect to our SQL Server database and perform CRUD operations.

Create ASP.NET Core WEB API Template Using Visual Studio 2019

We will open Visual Studio 2019 in which we will create our ASP.NET Core web API.

1. Click On Create A New Project

First, we will open Visual Studio 2019 and click on "Create a new project"

2. Select ASP.NET Core Web Application

3. Give A Name To Your ASP.NET Core Project

Give a name to your ASP.NET Core project and solution and also give it a path where you want to save your solution.

4. Select ASP.NET Core Version

From this window, please select the ASP.NET Core version that is installed in your system. In this example, we will use ASP.NET Core 3.1.

Click on the "Create" button to create the template project.

Create New Controller For ASP.NET Core Web API

It's now time to create a new API controller for our application. This new controller will be the API endpoint for our ASP.NET Core Web API.

We will right-click on the controller folder to add a new controller to our solution. 

Give it a valid name.

We are creating a new controller for our Employees endpoint. So, we will give the name of the controller as "EmployeesController".

In this controller, we will add Action methods to perform CRUD operations like GET, POST, PUT and DELETE.

Create Repository Interface and Repository Implementation - Repository Pattern In ASP.NET Core

We will now create a new folder in our solution. 

We will name this folder "EmployeeData".

In this folder, we will create a new interface called "IEmployeeInterface"

using RestApiTutorial.Models; using System; using System.Collections.Generic; namespace RestApiTutorial.EmployeeData { public interface IEmployeeData { Employee AddEmployee(Employee employee); List GetEmployees(); Employee GetEmployee(Guid id); void DeleteEmployee(Employee employee); Employee EditEmployee(Employee employee); } }

Install Entity Framework Core To Our ASP.NET Core API (EF Core)

Let's install Entity Framework core to our application.

"Right-Click" on dependencies and click on "Manage Nuget Packages".

From this nuget window, we will search and install the below packages


The second package we will install is Microsoft.EntityFrameworkCore.Tools

Create DbContext Using EntityFrameworkCore And Run Migrations

1. Create EmployeeContext Folder and EmployeeDbContext

Create a new EmployeeContext folder in your solution.

Then create a new class in this folder called EmployeeDbContext. This inherits from DbContext.

using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RestApiTutorial.Models { public class EmployeeDbContext: DbContext { public EmployeeDbContext(DbContextOptions dbContextOptions): base (dbContextOptions) { } public DbSet Employees { get; set; } } }

2. Create Employee Model And EF Core Data Annotations

using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace RestApiTutorial.Models { public class Employee { [Key] public Guid Id { get; set; } [Required] [MaxLength(50, ErrorMessage = "Name cannot be longer than 50 characters long")] public string Name { get; set; } } }

3. Add Connection String To AppSettings.json

{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "ConnectionStrings": { "EmployeeDbConnection": "server=.;database=EmployeeDB;Trusted_Connection=true" } }

4. Inject DbContext Into Services Using Dependency Injection

Now, we will use dependency injection and inject the EmployeeDbContext into our application services in the startup.cs file.

We will use the connection string that we created in the appsettings.json file and use it inside our startup.cs class to inject the EmployeeDbContext in our API services.

Open Startup.cs and add the below code.

services.AddScoped(); services.AddDbContextPool(options => options.UseSqlServer(Configuration.GetConnectionString("EmployeeDbConnection")));

5. Run Entity Framework Core Migrations (Ef Core Migrations)

Now, we will run EF Core migrations and create the new database inside our database.

To run migrations, go to Tools > Nuget Package Manager > Package Manager Console

Once the Package Manager Console is open, run the following commands one by one:

1. add-migrations "Initial Migration"

The wordings inside the quote could be anything that you like. Because this is the first migration, we will name it "Initial Migration"

2. update-database

Once the add-migrations command is over, run the update-database command and this command will create the database for you.

You can go ahead to SQL Server and check the progress. You should now have a new database in the server.

Create Repository Implementation For IEmployeeRepository

Now, it's time to create the repository implementation for IEmployeeRepository.

We will call this SqlEmployeeRepository.

Create a new class inside the same folder where we had the IEmployeeRepository.

As the repository implementation implements the IEmployeeRepository, we will create implementations for all the methods in the SqlEmployeeRepository.

We will use EF Core and the injected DbContext to connect and talk to our database.

The code for the SqlEmployeeDbContext will look like below:

using RestApiTutorial.Models; using System; using System.Collections.Generic; using System.Linq; namespace RestApiTutorial.EmployeeData { public class SqlEmployeeData : IEmployeeData { private EmployeeDbContext _employeeContext; public SqlEmployeeData(EmployeeDbContext employeeContext) { _employeeContext = employeeContext; } public Employee AddEmployee(Employee employee) { employee.Id = Guid.NewGuid(); _employeeContext.Employees.Add(employee); _employeeContext.SaveChanges(); return employee; } public void DeleteEmployee(Employee employee) { _employeeContext.Employees.Remove(employee); _employeeContext.SaveChanges(); } public Employee EditEmployee(Employee employee) { var currentEmployee = _employeeContext.Employees.Find(employee.Id); currentEmployee.Name = employee.Name; _employeeContext.Update(currentEmployee); _employeeContext.SaveChanges(); return currentEmployee; } public Employee GetEmployee(Guid id) { var employee = _employeeContext.Employees.Find(id); if(employee != null) { return employee; } return null; } public List GetEmployees() { return _employeeContext.Employees.ToList(); } } }

Use DbContext Inside Controller And Perform CRUD Operations

Now that we have created our new database and created a repository that performs CRUD operations, it's now time to inject this repository inside the controller.

The controller will have ActionMethods that implement CRUD operations.

The code for the controller will look like below:

using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using RestApiTutorial.EmployeeData; using RestApiTutorial.Models; using System; namespace RestApiTutorial.Controllers { [ApiController] public class EmployeesController : ControllerBase { private IEmployeeData _employeeData; public EmployeesController(IEmployeeData employeeData) { _employeeData = employeeData; } [HttpGet] [Route("api/[controller]")] public IActionResult GetEmployees() { return Ok(_employeeData.GetEmployees()); } [HttpGet] [Route("api/[controller]/{id}")] public IActionResult GetEmployee(Guid id) { var employee = _employeeData.GetEmployee(id); if (employee != null) { return Ok(employee); } return NotFound($"Employee with Id {id} was not found."); } [HttpPost] [Route("api/[controller]")] public IActionResult AddEmployee(Employee employee) { var createdEmployee = _employeeData.AddEmployee(employee); return Created( String.Format(HttpContext.Request.Scheme + "://" + HttpContext.Request.Host + HttpContext.Request.Path + "/" + employee.Id), employee); } [HttpDelete] [Route("api/[controller]/{id}")] public IActionResult DeleteEmployee(Guid id) { var employee = _employeeData.GetEmployee(id); if (employee != null) { _employeeData.DeleteEmployee(employee); return Ok(); } return NotFound($"Employee with Id {id} was not found."); } [HttpPatch] [Route("api/[controller]/{id}")] public IActionResult EditEmployee(Guid id, Employee employee) { var currentEmployee = _employeeData.GetEmployee(id); if(currentEmployee != null) { employee.Id = id; _employeeData.EditEmployee(employee); return Ok(); } return NotFound($"Employee with Id {employee.Id} was not found."); } } }

Run ASP.NET Core Web API and Test Using Postman

Our core web API is built and ready to be consumed.

We will use Postman to test our API.

We will call the API endpoints that we created and verify the results.

ASP.NET Core Web API CRUD - Video Tutorial