ASP.NET Clean Architecture: Implement the Presentation Layer

The Presentation Layer is the entry point of our application. It handles incoming HTTP requests, communicates with the Application Layer, and returns appropriate HTTP responses to API consumers.

In our Employee Management Web API, we will use ASP.NET Core Web API to expose employee-related operations through REST API endpoints.

ASP.NET Clean Architecture: Implement the Presentation Layer (Web API)

Getting Started

In the previous sections, we created project solution to repragent layer of Clean Architecture and implemented the Domain, Application, and Infrastructure Layers. Now, we will connect these layers and expose the employee CRUD operations through an API controller.

Let's implement the Presentation Layer step by step.

Step 1: Configure Dependency Injection

Before creating the controller, we need to register the Application and Infrastructure services with the ASP.NET Core dependency injection container.

Open Program.cs in the API project.Update it as follows:
</> C#
using CleanArchitectureDemo.Application;
using CleanArchitectureDemo.Infrastructure;
var builder = WebApplication.CreateBuilder(args);
// Register application services
builder.Services.AddApplication();
// Register infrastructure services
builder.Services.AddInfrastructure(
builder.Configuration);
// Register API services
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure HTTP request pipeline
if (app.Environment.IsDevelopment())
{
  app.UseSwagger();
  app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

Let's understand the important configurations:
  • AddApplication() registers application services such as EmployeeService.
  • AddInfrastructure() registers the database context and repository implementation.
  • AddControllers() registers controller support.
  • AddSwaggerGen() configures Swagger documentation.
  • MapControllers() maps controller endpoints to the HTTP request pipeline.

Step 2: Create Employee Controller

Right-click the Controllers folder and select Add → Controller. Choose an API Controller template or create an empty API controller. Name it EmployeesController.cs.

Note:- Create a folder named Controllers if it does not already exist.

EmployeesController.cs
</> C#
using CleanArchitectureDemo.Application.DTOs;
using CleanArchitectureDemo.Application.Interfaces;
using Microsoft.AspNetCore.Mvc;
namespace CleanArchitectureDemo.API.Controllers
{
  public class EmployeesController : Controller
  {
    private readonly IEmployeeService _employeeService;
    public EmployeesController(IEmployeeService employeeService)
    {
      _employeeService = employeeService;
    }
    // GET: api/employees
    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
      var employees = await _employeeService.GetAllAsync();
      return Ok(employees);
    }
    // GET: api/employees/5
    [HttpGet("{id}")]
    public async Task<IActionResult> GetById(int id)
    {
      var employee = await _employeeService.GetByIdAsync(id);
      if (employee == null)
      return NotFound("Employee not found.");
      return Ok(employee);
    }
    // POST: api/employees
    [HttpPost]
    public async Task<IActionResult> Create(
    CreateEmployeeDto dto)
    {
      var employeeId = await _employeeService.CreateAsync(dto);
      return CreatedAtAction(
      nameof(GetById),
      new { id = employeeId },
      new { id = employeeId });
    }
    // PUT: api/employees/5
    [HttpPut("{id}")]
    public async Task<IActionResult> Update(
    int id,
    UpdateEmployeeDto dto)
    {
      var result = await _employeeService.UpdateAsync(id, dto);
      if (!result)
      return NotFound("Employee not found.");
      return NoContent();
    }
    // DELETE: api/employees/5
    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(int id)
    {
      var result = await _employeeService.DeleteAsync(id);
      if (!result)
      return NotFound("Employee not found.");
      return NoContent();
    }
  }
}

Let's understand the implementation.
  1. Constructor Dependency Injection: We inject IEmployeeService into the controller through constructor injection. The controller communicates with the Application Layer through this interface instead of directly accessing the repository or database.
  2. GetAll(): Retrieves all employees and returns an HTTP 200 (OK) response.
  3. GetById(): Retrieves an employee using its ID. If the employee does not exist, it returns HTTP 404 (Not Found).
  4. Create(): Creates a new employee and returns HTTP 201 (Created) along with the newly generated employee ID and a location header pointing to the employee resource.
  5. Update(): Updates an existing employee. It returns HTTP 204 (No Content) when the operation succeeds or HTTP 404 when the employee does not exist.
  6. Delete(): Deletes an employee and returns HTTP 204 (No Content) when the operation succeeds or HTTP 404 when the employee does not exist.

Step 3: Understand the API Endpoints

Employee Management Web API now exposes the following endpoints:
HTTP Method Endpoint Description
GET /api/employees Retrieves all employees
GET /api/employees/{id} Retrieves an employee by ID
POST /api/employees Creates a new employee
PUT /api/employees/{id} Updates employee information
DELETE /api/employees/{id} Deletes an employee
These endpoints follow standard REST API conventions.

Step 4: Understand the Request Flow

When a client sends an HTTP request, the Presentation Layer receives the request and delegates the operation to the Application Layer.

For example, when creating a new employee, the request follows this flow:
</> Plain Text
Client / HTTP Request
POST /api/employees
Presentation Layer
EmployeesController
Application Layer
EmployeeService
Domain Layer
Employee entity and business rules
Infrastructure Layer
EmployeeRepository and ApplicationDbContext
SQL Server
Stores employee information

The response then travels back through the Application Layer and Presentation Layer to the client.

This separation ensures that controllers remain lightweight and application workflows are maintained independently of HTTP-related concerns.

Step 5: Run and Test the Web API

We have completed the Presentation Layer. Now, let's run the application and verify that our API endpoints are working correctly.

  1. Right-click CleanArchitectureDemo.API.
  2. Select Set as Startup Project.
  3. Press F5 or Ctrl + F5 to run the application.
  4. Open the Swagger UI page in your browser.

You should now see all the Employees API endpoints displayed in Swagger. In this step, simply verify that all the endpoints (controller actions) are available and properly listed in Swagger. We will perform a complete API testing walkthrough in an upcoming article.

Understand the API Project Structure

After completing above steps,the API project will contain:
</> Plain Text
CleanArchitectureDemo.API
│
├── Controllers
│   └── EmployeesController.cs
│
├── Program.cs
│
├── appsettings.json
│
└── Properties
The responsibilities of the Presentation Layer include:
  • Handling HTTP requests and responses.
  • Exposing REST API endpoints.
  • Performing request-level validation.
  • Communicating with Application Layer services.
  • Returning appropriate HTTP status codes.

Important: The example does not yet include authentication, authorization, centralized exception handling, or advanced request validation. These can be added as further improvements.

If you are not configuring authentication or authorization yet, you can remove app.UseAuthorization() from Program.cs. If you plan to use authorization, register it with builder.Services.AddAuthorization() first.

Summary

We have successfully implemented the Presentation Layer of our Employee Management Web API using ASP.NET Core.

In this section, we:
  • Configured dependency injection.
  • Created the Employees Controller.
  • Exposed REST API endpoints.
  • Implemented employee CRUD operations.
  • Tested the API using Swagger.

In the next article, we will integrate SQL Server with our application using Entity Framework Core. We will configure the database connection, create and apply migrations, and generate the database schema, including the Employee table, in SQL Server.

Stay tuned as we bring our Employee Management Web API one step closer to a fully functional application!

Thanks

Kailash Chandra Behera

I am an IT professional with over 12 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies.

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

نموذج الاتصال