.NET 8: ASP.Net Core Web API CRUD Operations

In .NET 8, Developing a CRUD (Create, Read, Update, Delete) API using In-memory collection is a common task in web development. In this article, we will explore building a complete .NET 8 ASP.NET Core Web API CRUD Operations. With a practical use case.

What is an API?

  • API stands for Application Programming Interface.
  • API is a software intermediary that allows different software applications to communicate and exchange data.

What is RESTful API?

  1. REST stands for Representational State Transfer.
  2. REST is a software architecture that imposes conditions on how an API should work.
  3. RESTful API is an interface that two computer systems use to exchange information securely over the internet.

Create an Asp.NET Core Web API Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project

  1. Open the visual studio (IDE).
  2. Click on the “Create new project” option.
  3. Choose “ASP.NET Core Web API” from the list of available templates.
  4. Click the Next button.
  5. The configure a new project, specify the name and location of your project.
  6. Click the “Next” button.
  7. Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  8. Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  9. Click the “Create” button

Once the project is created, let’s delete the existing WeatherForecast controller and model file.

Let’s create a folder in the project named

  • Model
  • Services

Right-click on Solution -> Add-> New Folder

Creating a Model

Right-click on Model Folder and select Add then click on New Item then enter class Name (Department.cs) and press the Add button.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {

        public int Id { get; set; }
        public required string DepartmentName { get; set; }
        public string Description { get; set; } = string.Empty;
        public bool IsActive { get; set; } = true;
    }
}

For Adding and updating the department list create another model AddUpdatedepartment.cs

namespace dotNet8CRUDWebAPI.Model
{
    public class AddUpdateDepartment
    {

        public required string DepartmentName { get; set; }
        public string Description { get; set; } = string.Empty;
        public bool IsActive { get; set; } = true;
    }
}

Create Services

Create an interface, Right click on Services Folder select Add, and click on New Item then select an interface and enter Interface Name(IDepartment.cs), and press the Add button.

In the interface, we are going to define business logic.

using dotNet8CRUDWebAPI.Model;

namespace dotNet8CRUDWebAPI.Services
{
    public interface IDepartment
    {
        List<Department> GetAllList(bool? IsActive);
        Department? GetById(int id);
        Department AddDeparement(AddUpdateDepartment DeptObj);
        Department? UpdateDepartment(int id, AddUpdateDepartment DeptObj);
        bool DeleteDepartmentById(int id);

    }
}

Create a concrete class, Right click on Services Folder and select Add, and click on New Item then select the class and enter class Name(DepartmentServices.cs) and press the Add button.

In the concrete class, we are going to implement the interface.


using dotNet8CRUDWebAPI.Model;

namespace dotNet8CRUDWebAPI.Services
{
    public class DepartmentServices : IDepartment
    {
        private readonly List<Department> _departmentList;

        public DepartmentServices()
        {
            _departmentList = new List<Department>()
            {
                new Department()
                {
                    Id = 1,
                    DepartmentName= "Computer Science",
                    Description = "Head of Department",
                    IsActive = true,


                }
            };
        }
        public List<Department> GetAllList(bool? IsActive)
        {
            return IsActive== null ? _departmentList : _departmentList.Where(dept=>dept.IsActive==IsActive).ToList();
        }

        public Department? GetById(int id)
        {
            return _departmentList.FirstOrDefault(dept=>dept.Id==id);
         }


        public Department AddDeparement(AddUpdateDepartment DeptObj)
        {
            var AddDepartment = new Department()
            {
                Id = _departmentList.Max(id=> id.Id) + 1,
                DepartmentName = DeptObj.DepartmentName,
                Description = DeptObj.Description,
                IsActive =DeptObj.IsActive
            };
            _departmentList.Add(AddDepartment);

            return AddDepartment;
        }
              
        
        
        public Department? UpdateDepartment(int id, AddUpdateDepartment DeptObj)
        {
            var Deptindex = _departmentList.FindIndex(idx => idx.Id==id);

            if(Deptindex>0)
            {
                var Dept = _departmentList[Deptindex];
                Dept.DepartmentName = DeptObj.DepartmentName;
                Dept.Description = DeptObj.Description;
                Dept.IsActive = DeptObj.IsActive;

                _departmentList[Deptindex] = Dept;

                return Dept;

            }
            else
            {
                return null;
            }

        }

        public bool DeleteDepartmentById(int id)
        {
            var deptindex = _departmentList.FindIndex(idx => idx.Id == id);
            if (deptindex>0)
            {
                _departmentList.RemoveAt(deptindex);
            }
            return deptindex>0;
        }

    }
}

Creating a  Controller

Create a Controller, Right-click on Controller Folder select Add -> Controller -> API -> API Controller, and enter controller Name (DepartmentController.cs) and press the Add button.

  • Open the DepartmentController file
  • Create a constructor and inject the IDepartment interface
  • Create action methods
    • GET
    • POST
    • PUT
    • Delete
using dotNet8CRUDWebAPI.Model;
using dotNet8CRUDWebAPI.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace dotNet8CRUDWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DepartmentController : ControllerBase
    {
        private readonly IDepartment _department;

        public DepartmentController(IDepartment department)
        {
           _department = department;
        }

        [HttpGet]
        public IActionResult Get([FromQuery] bool? isActive=null)
        {
            return Ok(_department.GetAllList(isActive));
        }
        [HttpGet]
        [Route("{id}")]
        public  IActionResult Get(int id)
        {
            var dept = _department.GetById(id);
            if (dept == null)
            {
                return NotFound();
            }
            return Ok(dept);

        }

        [HttpPost]
        public IActionResult Post(AddUpdateDepartment obj)
        {
            var dept = _department.AddDeparement(obj);
            if(dept == null)
            {
                return BadRequest();
            }
            return Ok(new
            {
                message = "Deparment Created Successfully...!",
                id = dept!.Id
            });
        }

        [HttpPut]
        [Route("{id}")]
        public IActionResult Put([FromRoute] int id, [FromBody]  AddUpdateDepartment obj)
        {
            var dept = _department.UpdateDepartment(id, obj);
            if (dept == null)
            {
                return NotFound();
            }
            return Ok(new
            {
                message = "Deparement Updated Successfully...!",
                id = dept!.Id
            });
        }

        [HttpDelete]
        [Route("{id}")]
        public IActionResult Delete([FromRoute]int id)
        {
            
            if (!_department.DeleteDepartmentById(id))
            {
                return NotFound();
            }
            return Ok(new {
                message = "Department Deleted Successfully..!",
                id = id
            });
        }
    }
}

Register services

Open the Program.cs file and register IDepartment and DepartmentServices as an AddSingleton.

using dotNet8CRUDWebAPI.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

builder.Services.AddSingleton<IDepartment,DepartmentServices>();
var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Run the API Project

Get All Department List

Adding a Deparments

.NET 8: ASP.Net Core Web API CRUD Operations

Updating Department

.NET 8: ASP.Net Core Web API CRUD Operations

Delete a Department

.NET 8: ASP.Net Core Web API CRUD Operations

See More: How to Avoid Data Overload in EF Core

One Comment on “.NET 8: ASP.Net Core Web API CRUD Operations”

  1. I really got into this article. I found it to be interesting and loaded with unique points of interest. I like to read material that makes me think. Thank you for writing this great content.

Leave a Reply

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