Introduction
Imagine you are developing an employee management application for an organization.
The application has an Angular frontend where HR employees can view employee details, add new employees, update information, and manage records.
Now consider another requirement: the organization also wants to access the same employee information through a mobile application.
Would you develop the same business logic separately for Angular and the mobile application?
That would create unnecessary duplication and make the application harder to maintain.
A better approach is to develop a centralized backend that exposes functionality through HTTP endpoints. Both applications can communicate with this backend.
This is where .NET Core Web API comes into the picture.
In this tutorial, we'll understand how .NET Core Web API fits into application development, how client-server communication works, and how to create a small practical API using C#.
1. Understanding the problem before understanding Web API
Let's take our employee management application as an example.
We have three requirements:
The HR team needs to retrieve employee information.
The HR team needs to add new employees.
The mobile application needs access to the same employee information.
We could build separate backend implementations for each client, but that would duplicate business logic.
Instead, we can build one backend application that exposes endpoints.
For example:
| Operation | HTTP endpoint |
|---|---|
| Get all employees | GET /api/employees |
| Get employee by ID | GET /api/employees/1 |
| Add employee | POST /api/employees |
| Update employee | PUT /api/employees/1 |
| Delete employee | DELETE /api/employees/1 |
Now Angular, mobile applications, or other authorized clients can consume these endpoints.
The backend handles the operations and returns the appropriate responses.
2. What exactly is .NET Core Web API?
An API stands for Application Programming Interface.
A Web API is an interface that allows applications to communicate over a network using web protocols such as HTTP and HTTPS.
.NET Core Web API is the familiar name developers use for building HTTP-based backend services using C# and ASP.NET Core.
It provides functionality to:
Receive HTTP requests.
Execute application logic.
Validate incoming data.
Communicate with databases.
Authenticate and authorize clients.
Return HTTP responses.
Integrate with external services.
For example, an Angular application can call a .NET Core Web API endpoint to retrieve employee records.
The Angular application doesn't need to know how the backend retrieves information from SQL Server. It only needs to understand the API contract.
A useful distinction: The series uses the familiar term .NET Core Web API. Our practical examples will use modern ASP.NET Core with .NET 8 and .NET 10. .NET Core was renamed to .NET starting with .NET 5.
3. How does .NET Core Web API communicate with other applications?
Let's understand the communication process using our employee management application.
Suppose an HR employee opens the employee list page in Angular.
Step 1: Client sends a request
Angular sends an HTTP GET request:
GET https://localhost:7001/api/employees
Accept: application/jsonStep 2: Web API receives the request
The .NET Core Web API receives the request and identifies the endpoint responsible for retrieving employees.
Step 3: Application processes the request
The backend executes the required application logic and retrieves employee records.
Step 4: API prepares the response
The API converts the result into an appropriate HTTP response, commonly containing JSON data.
Step 5: Client displays the result
Angular receives the response and displays the employee information.
This is the basic request-response communication model.
4. Understanding the architecture through a real application
A maintainable .NET Core Web API application can be organized into different responsibilities.
Let's consider the following structure:
EmployeeManagement
│
├── Controllers
│ └── EmployeesController.cs
│
├── Models
│ └── Employee.cs
│
├── DTOs
│ └── EmployeeDto.cs
│
├── Services
│ └── EmployeeService.cs
│
├── Data
│ └── ApplicationDbContext.cs
│
├── Program.cs
│
└── appsettings.jsonEach component has a different responsibility.
Controllers: Handle incoming HTTP requests and return HTTP responses.
Models: Represent application data and domain objects.
DTOs: Define the data that enters or leaves the API.
Services: Contain business operations and application logic.
Data: Contains database-related functionality, such as Entity Framework Core DbContext.
Program.cs: Configures application services and the HTTP request pipeline.
This is an illustrative organization. A small API may use fewer folders, while a larger application may separate these responsibilities into different projects.
5. Let's build a simple .NET Core Web API
Now let's understand the concept through a small practical example.
We'll create an employee API that returns employee information.
Step 1: Create a Web API project
Open Visual Studio or your terminal.
Using the .NET CLI:
dotnet new webapi -n EmployeeManagementNavigate to the project:
cd EmployeeManagementRun the application:
dotnet runThe application will start using the configured development URLs.
You can also create the project using Visual Studio:
Open Visual Studio.
Select Create a new project.
Choose ASP.NET Core Web API.
Enter the project name.
Select .NET 8 or .NET 10.
Configure the project and create it.
For this tutorial, we'll use a controller-based API.
Step 2: Create an Employee model
Create a folder named Models.
Inside it, create Employee.cs.
namespace EmployeeManagement.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Department { get; set; } = string.Empty;
public decimal Salary { get; set; }
}
}This class represents an employee in our application.
For this introductory example, we'll use an in-memory collection rather than a database.
Step 3: Create an EmployeesController
Create a folder named Controllers.
Add a controller named EmployeesController.cs.
using Microsoft.AspNetCore.Mvc;
using EmployeeManagement.Models;
namespace EmployeeManagement.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class EmployeesController : ControllerBase
{
private static readonly List<Employee> Employees = new()
{
new Employee
{
Id = 1,
Name = "John",
Department = "IT",
Salary = 50000
},
new Employee
{
Id = 2,
Name = "David",
Department = "HR",
Salary = 45000
}
};
[HttpGet]
public IActionResult GetEmployees()
{
return Ok(Employees);
}
}
}Let's understand the important parts.
[ApiController]
This attribute enables API-specific behavior, including automatic model validation responses in supported scenarios.
[Route("api/[controller]")]
This defines the route for the controller.
Since the controller is named EmployeesController, its route becomes:
/api/employeesControllerBase
ControllerBase provides functionality commonly required by API controllers, including methods such as Ok(), NotFound(), and BadRequest().
[HttpGet]
This attribute identifies the action as an HTTP GET endpoint.
Ok(Employees)
This returns an HTTP 200 OK response containing the employee collection.
Step 4: Configure Program.cs
In modern ASP.NET Core applications, Program.cs is the main entry point used to register services and configure the request pipeline.
For a controller-based application, make sure it contains the following configuration:
var builder = WebApplication.CreateBuilder(args);
// Register controller services
builder.Services.AddControllers();
// Register API endpoint exploration
builder.Services.AddEndpointsApiExplorer();
// Build the application
var app = builder.Build();
// Configure HTTP request pipeline
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
// Map controller routes
app.MapControllers();
app.Run();If your project template already contains additional configuration, retain the relevant existing settings and integrate the controller configuration rather than blindly replacing the entire file.
Step 5: Test your API
Run the application and open Swagger UI in your browser if it is enabled.
You should see the following endpoint:
GET /api/employeesExecute the request.
Expected response:
[
{
"id": 1,
"name": "John",
"department": "IT",
"salary": 50000
},
{
"id": 2,
"name": "David",
"department": "HR",
"salary": 45000
}
]<Note>For this introductory example, the employee records are stored in a static in-memory collection. They are not persisted in SQL Server, and changes to them are not durable across application restarts.</Note>
Congratulations! You've created a basic .NET Core Web API endpoint.
6. Why should we use .NET Core Web API?
Let's understand the practical advantages.
1. Multiple clients, one backend
The same API can serve Angular, React, mobile applications, and other authorized systems.
2. Separation of responsibilities
The frontend handles presentation, while the backend manages business operations and data access.
3. Cross-platform support
Modern .NET applications can run on Windows, Linux, and macOS.
4. Built-in dependency injection
ASP.NET Core provides dependency injection, which helps organize services and manage their dependencies.
5. Security support
ASP.NET Core supports authentication and authorization mechanisms, including JWT bearer authentication and role-based access control.
6. Integration with databases
You can connect your API with SQL Server using Entity Framework Core, Dapper, or ADO.NET.
7. Performance and scalability
ASP.NET Core provides a high-performance platform for developing backend services that can be deployed and scaled according to application requirements.
7. Where are .NET Core Web APIs used?
Here are some practical examples:
| Application | API responsibilities |
|---|---|
| Employee management | Employees, departments, attendance |
| E-commerce | Products, carts, orders |
| Banking | Accounts, transactions |
| Healthcare | Appointments, patient records |
| Learning management | Courses, students, results |
| CRM | Customers, leads, sales |
For example, an employee management system may use one API for employee information, another for attendance, and another for reporting.
These APIs can share common services and database infrastructure.
8. Important concepts to learn next
Understanding what a Web API is gives us the foundation. However, building production-ready APIs requires knowledge of additional concepts.
Here are some topics we'll cover in this series:
HTTP methods and status codes.
Routing and route parameters.
Controllers and Minimal APIs.
Dependency injection.
DTOs and model validation.
Entity Framework Core.
SQL Server integration.
Authentication and authorization.
Exception handling and logging.
API versioning and pagination.
Testing and deployment.
9. Interview Questions
Q1. What is .NET Core Web API?
.NET Core Web API is a commonly used name for HTTP services developed using ASP.NET Core. It allows different client applications to communicate with backend services through HTTP or HTTPS.
Q2. Can a .NET Core Web API support multiple frontend applications?
Yes. The same API can serve different clients, provided they have the required access and follow the API contract.
Q3. What is the difference between a Web API and a web application?
A web application generally provides a user-facing interface, whereas a Web API exposes endpoints that clients use to access backend functionality. An application can contain both.
Q4. What is the purpose of a controller in .NET Core Web API?
A controller handles incoming HTTP requests, executes the corresponding action, and returns an HTTP response.
Q5. What is the role of Program.cs?
Program.cs is the application entry point where services are registered and the HTTP request pipeline is configured in modern ASP.NET Core applications.
Q6. Does a Web API always require a database?
No. An API can return information from an in-memory collection, an external service, a file, or a database. The data source depends on the application requirements.
Conclusion
.NET Core Web API is an important part of modern backend development using C#.
Instead of creating separate backend implementations for different client applications, we can expose centralized endpoints that handle business operations and provide consistent access to application data.
In this tutorial, we explored the purpose of Web APIs, their communication flow, a typical application architecture, and created a basic employee API.
In the next article, we'll go one level deeper and understand what happens inside a .NET Core Web API when a client sends an HTTP request.
Next Tutorial: Day 2 – How .NET Core Web API Works Internally?
Skills Tutorials – Learn • Build • Grow Together
Part of our 30 Days of .NET Core Web API learning series.
No comments:
Post a Comment