LEARN BUILD GROW TOGETHER
Practical knowledge for developers
DEVELOPER LEARNING HUB
Learn. Build. Grow Together.

Practical tutorials, real-world examples and interview preparation.

.NETC#SQL SERVERANGULAR

HTTP Methods in .NET Core Web API: GET, POST, PUT, PATCH and DELETE Explained

November 3, 2026 5 min read , , , , ,

 

Introduction

In the previous article, we learned how a .NET Core Web API processes an incoming HTTP request, executes the required logic, and returns a response to the client.

Now let's understand an important part of that communication: HTTP Methods.

Imagine you are developing an Employee Management application. Users should be able to:

  • View all employees.

  • View a particular employee.

  • Add a new employee.

  • Update existing employee information.

  • Delete an employee record.

How does the client tell the API which operation it wants to perform?

This is where HTTP methods come into the picture.

HTTP methods describe the intended operation that a client wants to perform on a resource.

In this article, we'll understand five commonly used HTTP methods and implement them using C# in a .NET Core Web API.

1. What are HTTP Methods?

HTTP methods are part of the HTTP protocol. They indicate the intended action for a particular request.

For example, consider this API endpoint:

/api/employees

The same endpoint can support different operations depending on the HTTP method.

HTTP methodPurposeExample
GETRetrieve dataGet employees
POSTCreate a resourceAdd an employee
PUTReplace an existing resourceUpdate employee details
PATCHPartially update a resourceChange employee department
DELETEDelete a resourceRemove an employee

Notice that the URL can remain the same while the HTTP method changes.

For example:

GET    /api/employees
POST   /api/employees
GET    /api/employees/101
PUT    /api/employees/101
PATCH  /api/employees/101
DELETE /api/employees/101

The API identifies the operation using both the HTTP method and the requested URL.

2. Understand CRUD operations and HTTP methods

Before writing code, let's connect HTTP methods with CRUD operations.

CRUD stands for:

  • Create

  • Read

  • Update

  • Delete

These are the four fundamental operations performed on application data.

CRUD operationHTTP methodEmployee example
CreatePOSTAdd a new employee
ReadGETView employee details
UpdatePUT / PATCHModify employee information
DeleteDELETERemove an employee

For example, when an administrator adds a new employee, the client sends a POST request.

When the administrator opens the employee list, the client sends a GET request.

This mapping is commonly used when designing RESTful APIs.

3. GET – Retrieve data

The GET method is used to retrieve information from the server.

It should not be used to create, delete, or modify application resources.

Consider an Employee Management application.

You want to retrieve all employees.

API endpoint:

GET /api/employees

You can also retrieve a particular employee using their ID:

GET /api/employees/101

C# implementation

[HttpGet]
public IActionResult GetEmployees()
{
    return Ok(Employees);
}

[HttpGet("{id:int}")]
public IActionResult GetEmployeeById(int id)
{
    var employee = Employees.FirstOrDefault(x => x.Id == id);

    if (employee is null)
    {
        return NotFound(new
        {
            Message = "Employee not found."
        });
    }

    return Ok(employee);
}

Expected response

Request:

GET /api/employees/101

Response:

{
  "id": 101,
  "name": "Rahul",
  "department": "IT"
}

Status code:

200 OK

If the employee does not exist, the API returns:

404 Not Found

Important points about GET

  • GET is used to retrieve resources.

  • It should not modify server-side resource state.

  • GET requests are considered safe.

  • GET is idempotent, meaning repeating the same request should have the same intended effect on server state.

  • GET responses can be cached when appropriate HTTP caching rules permit it.

4. POST – Create a new resource

The POST method is commonly used to create a new resource.

Suppose an administrator wants to add a new employee to the system.

The client sends employee information in the request body.

API endpoint:

POST /api/employees

Request body:

{
  "name": "Amit",
  "department": "Finance"
}

C# implementation

[HttpPost]
public IActionResult CreateEmployee(Employee employee)
{
    employee.Id = Employees.Count == 0
        ? 1
        : Employees.Max(x => x.Id) + 1;

    Employees.Add(employee);

    return CreatedAtAction(
        nameof(GetEmployeeById),
        new { id = employee.Id },
        employee
    );
}

Expected response

Status code:

201 Created

Response:

{
  "id": 103,
  "name": "Amit",
  "department": "Finance"
}

CreatedAtAction() returns a 201 Created response and includes a location identifying the newly created resource.

Important points about POST

  • POST is commonly used to create resources.

  • Data is generally sent in the request body.

  • POST is not inherently idempotent.

  • Sending the same POST request multiple times may create multiple resources unless the application implements duplicate prevention or idempotency handling.

Real-world example: When a user submits a registration form, the frontend can send a POST request to create a new user account.

5. PUT – Update an existing resource

The PUT method is generally used to replace the current representation of a resource with the representation provided in the request.

Suppose an employee has the following details:

{
  "id": 101,
  "name": "Rahul",
  "department": "IT"
}

Now the administrator wants to update the employee's information.

API endpoint:

PUT /api/employees/101

Request body:

{
  "name": "Rahul Sharma",
  "department": "Engineering"
}

C# implementation

[HttpPut("{id:int}")]
public IActionResult UpdateEmployee(int id, Employee updatedEmployee)
{
    var employee = Employees.FirstOrDefault(x => x.Id == id);

    if (employee is null)
    {
        return NotFound(new
        {
            Message = "Employee not found."
        });
    }

    employee.Name = updatedEmployee.Name;
    employee.Department = updatedEmployee.Department;

    return Ok(employee);
}

Expected response

Status code:

200 OK

Response:

{
  "id": 101,
  "name": "Rahul Sharma",
  "department": "Engineering"
}

Important points about PUT

  • PUT is generally used to replace a resource representation.

  • The client normally sends the complete representation of the resource being updated.

  • PUT is idempotent.

  • Sending the same PUT request multiple times should produce the same intended final resource state.

Important distinction: PUT does not automatically update a database record. The controller or application logic must perform the actual update operation.

6. PATCH – Partially update a resource

PATCH is used when you want to update only a specific part of an existing resource.

Let's understand this with the same employee example.

Current employee information:

{
  "id": 101,
  "name": "Rahul",
  "department": "IT"
}

Suppose the employee changes departments, but their name remains the same.

You only need to update the department.

API endpoint:

PATCH /api/employees/101

Request body:

{
  "department": "Engineering"
}

C# implementation

For this example, we'll create a small request model containing only the field that can be changed.

public class UpdateEmployeeDepartmentRequest
{
    public string Department { get; set; } = string.Empty;
}

Now add the PATCH action:

[HttpPatch("{id:int}")]
public IActionResult UpdateEmployeeDepartment(
    int id,
    UpdateEmployeeDepartmentRequest request)
{
    var employee = Employees.FirstOrDefault(x => x.Id == id);

    if (employee is null)
    {
        return NotFound(new
        {
            Message = "Employee not found."
        });
    }

    employee.Department = request.Department;

    return Ok(employee);
}

Expected response

Status code:

200 OK

Response:

{
  "id": 101,
  "name": "Rahul",
  "department": "Engineering"
}

Notice that only the department was changed. The employee's name remained unchanged.

Important points about PATCH

  • PATCH is used for partial updates.

  • The client sends only the information required for the update.

  • PATCH is not inherently idempotent, although a particular PATCH operation can be designed to be idempotent.

  • PATCH does not require you to use a particular request-body format. The API and its documentation should define the expected patch format.

Real-world example: A profile management application may allow a user to update only their phone number without submitting their entire profile again.

7. DELETE – Remove a resource

The DELETE method is used to request the removal of a resource.

Suppose an administrator wants to remove employee ID 101.

API endpoint:

DELETE /api/employees/101

C# implementation

[HttpDelete("{id:int}")]
public IActionResult DeleteEmployee(int id)
{
    var employee = Employees.FirstOrDefault(x => x.Id == id);

    if (employee is null)
    {
        return NotFound(new
        {
            Message = "Employee not found."
        });
    }

    Employees.Remove(employee);

    return NoContent();
}

Expected response

Status code:

204 No Content

A 204 response means the operation succeeded and there is no response body.

Important points about DELETE

  • DELETE is used to remove a resource.

  • DELETE is idempotent in terms of its intended effect on server state.

  • Repeating a DELETE request should not delete additional copies of the same resource.

  • The response to a repeated request does not have to be identical. For example, the first request might return 204 and a later request might return 404.

Real-world example: When an administrator removes an employee from an application, the frontend sends a DELETE request to the API.

8. Difference between PUT and PATCH

This is one of the most common questions asked during .NET developer interviews.

Both PUT and PATCH are used to update resources, but their intended behavior is different.

Consider an employee record:

{
  "id": 101,
  "name": "Rahul",
  "department": "IT",
  "location": "Delhi"
}

Now suppose you want to change only the department.

Using PUT

A PUT request generally provides the complete replacement representation:

{
  "name": "Rahul",
  "department": "Engineering",
  "location": "Delhi"
}

Using PATCH

A PATCH request can provide only the field that needs to change:

{
  "department": "Engineering"
}
ComparisonPUTPATCH
PurposeReplace resource representationPartially modify resource
Request bodyGenerally complete representationOnly required changes
IdempotentYesNot inherently
Common useUpdating employee detailsUpdating one employee field

Remember: The exact update behavior depends on how the API implements its PUT and PATCH operations.

9. Complete HTTP methods comparison

Let's summarize all five methods.

MethodOperationRequest bodyTypical success status
GETRetrieveUsually no200 OK
POSTCreateUsually yes201 Created
PUTReplaceUsually yes200 OK or 204 No Content
PATCHPartial updateUsually yes200 OK or 204 No Content
DELETEDeleteUsually no204 No Content

These are common patterns, not mandatory response codes for every possible API implementation.

10. Test the API using Postman

After implementing the controller, you can test the endpoints using Postman.

Follow these steps:

  1. Run your .NET Core Web API application.

  2. Open Postman.

  3. Select the required HTTP method.

  4. Enter the API URL.

  5. For POST, PUT, and PATCH, select Body → raw → JSON.

  6. Enter the request JSON.

  7. Click Send.

  8. Check the response body and status code.

Here are the requests you can test:

OperationMethodURL
Get all employeesGET/api/employees
Get employee by IDGET/api/employees/101
Create employeePOST/api/employees
Replace employeePUT/api/employees/101
Update departmentPATCH/api/employees/101
Delete employeeDELETE/api/employees/101

Note: The example uses an in-memory list. Data is not permanently saved, and restarting the application resets the list. We'll introduce database connectivity later in Week 2.

11. Common mistakes developers should avoid

1. Using GET to modify data

GET should retrieve resources, not perform operations that change server-side state.

2. Using POST for every operation

Although POST can support many types of processing, use the HTTP method that accurately describes the intended operation when designing a resource-oriented API.

3. Confusing PUT and PATCH

PUT generally replaces a resource representation, while PATCH applies partial modifications.

4. Ignoring status codes

A successful API response and a failed API response should not return the same status code. Use meaningful HTTP status codes.

5. Assuming DELETE always physically removes a database record

Real applications may implement soft deletion, where a record is marked inactive instead of being physically deleted.

6. Forgetting input validation

An API should validate incoming data before processing it. We'll cover DTOs and model validation in Day 9.

12. Interview questions

Q1. What are HTTP methods in Web API?

HTTP methods indicate the intended operation that a client wants to perform on a resource. Common methods include GET, POST, PUT, PATCH, and DELETE.

Q2. What is the difference between POST and PUT?

POST is commonly used to create resources or submit data for processing. PUT is generally used to replace an existing resource representation. POST is not inherently idempotent, whereas PUT is idempotent.

Q3. What is the difference between PUT and PATCH?

PUT generally replaces the resource representation, whereas PATCH applies partial modifications to a resource.

Q4. Which HTTP method is used to retrieve data?

GET is used to retrieve data from an API.

Q5. Which HTTP method is used to delete a resource?

DELETE is used to request the removal of a resource.

Q6. What is an idempotent HTTP method?

An idempotent method is one where making the same request multiple times has the same intended effect on server state as making it once. GET, PUT, and DELETE are idempotent methods.

Q7. Is POST idempotent?

POST is not inherently idempotent. Repeating the same POST request may create multiple resources unless the application implements idempotency or duplicate prevention.

Q8. What is the difference between 200 OK and 201 Created?

200 OK indicates that the request was successfully processed. 201 Created indicates that the request resulted in the creation of a resource.

Q9. What does 204 No Content mean?

It means the request was successfully processed, but the server has no response content to return.

Q10. Can we use the same URL for different HTTP methods?

Yes. For example, /api/employees can support GET to retrieve employees and POST to create an employee. Routing uses the HTTP method and URL to identify the appropriate endpoint.

Conclusion

HTTP methods are fundamental to building well-designed .NET Core Web APIs.

Understanding when to use GET, POST, PUT, PATCH, and DELETE helps you design predictable APIs and communicate effectively with frontend applications.

In our Employee Management example, we used:

  • GET to retrieve employees.

  • POST to create an employee.

  • PUT to replace employee information.

  • PATCH to update a specific field.

  • DELETE to remove an employee.

Now you have a practical understanding of how CRUD operations map to HTTP methods.

What's next?

In Day 4, we'll explore Minimal APIs vs Controllers in .NET Core Web API.

We'll understand both approaches, compare their architecture, explore their code structure, and learn when to choose each approach while building real-world applications.


Skills Tutorials – Learn • Build • Grow Together

Continue learning with our 30-day .NET Core Web API series.

How .NET Core Web API Works: Request and Response Lifecycle Explained

 

Introduction

In Day 1, we learned what .NET Core Web API is, why it is used, and how it acts as a bridge between a client application and a backend system.

Now let's understand something more important:

What actually happens when a client sends a request to a .NET Core Web API?

Suppose you are building an Employee Management application. An Angular application displays employee information, and the backend is developed using .NET Core Web API.

When a user opens the employee list, Angular sends an HTTP request to the API. The API receives that request, processes it, communicates with the application logic or database when required, and sends a response.

But several things happen between receiving the request and returning the response.

In this article, we'll understand that complete process step by step.

1. Understand the client-server communication

Before exploring the internal API pipeline, let's understand the two sides involved.

Client application

The client is the application that makes a request to the API. It could be:

  • Angular application

  • React application

  • Mobile application

  • Desktop application

  • Another backend service

  • Postman or another API testing tool

Backend API

The .NET Core Web API receives the request, executes the required logic, and returns a response.

For example, when a user opens the employee list, the Angular application sends:

GET https://localhost:7001/api/employees

The API processes this request and might return:

[
  {
    "id": 101,
    "name": "Rahul",
    "department": "IT"
  },
  {
    "id": 102,
    "name": "Priya",
    "department": "HR"
  }
]

The Angular application reads this JSON response and displays the employees on the screen.

The important point is that the client and API communicate through HTTP, using a request-response model.

2. Understand the complete request-response lifecycle

Let's follow one practical example.

Imagine a user wants to view the details of employee ID 101.

The Angular application sends:

GET /api/employees/101

The request travels through several stages inside the .NET application.

Request processing flow:

  1. Client sends an HTTP request.

  2. Kestrel receives the incoming request.

  3. Middleware components process the request.

  4. Routing identifies the matching endpoint.

  5. The framework prepares the controller action and its parameters.

  6. The controller executes the required application logic.

  7. The application retrieves the employee data.

  8. The result is converted into an HTTP response.

  9. The response travels back to the client.

Let's understand each stage.

3. Step 1 – Client sends an HTTP request

The process starts when the client application makes an API call.

For example, an Angular application might use:

this.http.get<Employee>(
  'https://localhost:7001/api/employees/101'
).subscribe({
  next: (employee) => {
    console.log(employee);
  },
  error: (error) => {
    console.error(error);
  }
});

Here:

  • http.get() sends an HTTP GET request.

  • The URL identifies the API endpoint.

  • The API receives the request.

  • The response is handled inside the subscription.

The client does not directly access the backend database. It communicates with the API, which controls how data is accessed.

4. Step 2 – Kestrel receives the request

When a request reaches a .NET application, it needs a web server to receive and handle the incoming HTTP connection.

In modern ASP.NET Core applications, the default cross-platform web server is Kestrel.

Kestrel is responsible for accepting network connections and receiving HTTP requests. It then passes the request into the ASP.NET Core request-processing pipeline.

For example, when your application runs locally:

https://localhost:7001

Kestrel listens on the configured endpoint and handles incoming requests.

You can see the application startup configuration in Program.cs.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();

app.Run();

This is a simplified controller-based application setup.

When the application starts, it creates and configures the web host, which runs the application and its request-processing pipeline.

Important: Kestrel is the web server. It does not contain your employee business logic. Its job is to receive and handle HTTP traffic.

5. Step 3 – Middleware processes the request

This is one of the most important concepts in .NET Core Web API.

Middleware components are software components arranged in a pipeline. Each component can inspect an HTTP request, perform an operation, pass control to the next component, and potentially process the response while it travels back.

Common middleware responsibilities include:

  • Exception handling

  • HTTPS redirection

  • Static file handling

  • Authentication

  • Authorization

  • CORS

  • Request logging

Consider this example:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.MapControllers();

app.Run();

Here, middleware and endpoint configuration determine how incoming requests are handled.

For example, HTTPS redirection can redirect an HTTP request to HTTPS before it reaches the controller.

How does middleware work?

Imagine three middleware components:

Incoming Request
       |
       v
Middleware A
       |
       v
Middleware B
       |
       v
Middleware C
       |
       v
Controller / Endpoint
       |
       v
Outgoing Response

The request moves forward through the pipeline.

After the endpoint finishes processing, the response travels back through the middleware components in reverse order.

This is why middleware can perform work both before and after the next component executes.

Practical middleware example

Let's create a simple request-logging middleware.

Add the following code before app.Run() in Program.cs:

app.Use(async (context, next) =>
{
    Console.WriteLine(
        $"Incoming Request: {context.Request.Method} " +
        $"{context.Request.Path}");

    await next();

    Console.WriteLine(
        $"Outgoing Response: {context.Response.StatusCode}");
});

Now when a client calls:

GET /api/employees/101

You may see:

Incoming Request: GET /api/employees/101
Outgoing Response: 200

This is a simple example of how middleware can help monitor API requests and responses.

Notice the await next() statement. It allows the request to continue to the next middleware component. Once downstream processing completes, execution resumes after that statement.

6. Step 4 – Routing identifies the endpoint

After the request passes through the relevant middleware, routing determines which endpoint should handle it.

Consider this controller:

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class EmployeesController : ControllerBase
{
    [HttpGet("{id:int}")]
    public IActionResult GetEmployee(int id)
    {
        return Ok(new
        {
            Id = id,
            Name = "Rahul",
            Department = "IT"
        });
    }
}

Let's understand the routing attributes.

[Route("api/[controller]")]

The [controller] token is replaced with the controller name without the Controller suffix.

For EmployeesController, the route becomes:

api/employees

[HttpGet("{id:int}")]

This identifies an HTTP GET endpoint with an integer route parameter.

The complete URL becomes:

GET /api/employees/101

When this request reaches the application, routing matches it with the GetEmployee action.

If the URL does not match an available endpoint, the application can return a 404 Not Found response.

7. Step 5 – Model binding prepares the action parameters

Once an endpoint has been selected, ASP.NET Core prepares the parameters required by the action method.

This process is called Model Binding.

For example:

[HttpGet("{id:int}")]
public IActionResult GetEmployee(int id)
{
    return Ok(new
    {
        Id = id,
        Name = "Rahul"
    });
}

The client sends:

GET /api/employees/101

The framework extracts 101 from the route and binds it to the id parameter.

The action receives:

id = 101

Model binding can obtain data from different request sources, including:

  • Route parameters

  • Query strings

  • Request bodies

  • Form fields

  • Request headers

For example, consider a query-string parameter:

[HttpGet]
public IActionResult GetEmployees([FromQuery] string department)
{
    return Ok(new
    {
        Department = department
    });
}

Request:

GET /api/employees?department=IT

The value IT is bound to the department parameter.

You can explicitly specify binding sources using attributes such as [FromRoute], [FromQuery], [FromBody], and [FromHeader].

8. Step 6 – Controller executes the application logic

After routing and parameter preparation, the selected controller action executes.

In a real application, a controller should not contain all the business logic or database operations.

A better approach is to keep responsibilities separate.

For example:

EmployeesController
       |
       v
EmployeeService
       |
       v
EmployeeRepository
       |
       v
SQL Server

Each component has a separate responsibility.

Controller: Handles the incoming HTTP request and produces the HTTP response.

Service: Contains application or business logic.

Repository: Handles data access when a repository pattern is used.

Database: Stores the employee records.

This separation makes the application easier to maintain, test, and extend.

We'll explore Dependency Injection in Day 8 of this series.

For now, understand that the controller is the entry point for the application endpoint, not necessarily the place where all business operations should be implemented.

9. Step 7 – API creates and returns the response

After processing the request, the controller returns a result.

For example:

[HttpGet("{id:int}")]
public IActionResult GetEmployee(int id)
{
    var employee = new
    {
        Id = id,
        Name = "Rahul",
        Department = "IT"
    };

    return Ok(employee);
}

The Ok() method creates an HTTP 200 OK response.

ASP.NET Core's result execution and output formatting mechanisms serialize the returned object into JSON by default for a typical JSON API response.

The client receives:

HTTP/1.1 200 OK
Content-Type: application/json

Response body:

{
  "id": 101,
  "name": "Rahul",
  "department": "IT"
}

The client can now use this data to display employee details.

Common HTTP response status codes

An API response contains a status code that indicates the outcome of the request.

Status codeMeaningExample
200OKEmployee retrieved successfully
201CreatedNew employee created
204No ContentOperation completed without a response body
400Bad RequestInvalid request data
401UnauthorizedAuthentication is required or invalid
403ForbiddenUser is not allowed to access the resource
404Not FoundEmployee does not exist
500Internal Server ErrorUnexpected server-side failure

We'll explore HTTP methods in detail in Day 3 and authentication and authorization later in Week 3.

10. Complete practical example

Let's connect the concepts with a small controller-based example.

Create an EmployeesController.cs file:

using Microsoft.AspNetCore.Mvc;

namespace EmployeeManagement.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class EmployeesController : ControllerBase
{
    private static readonly List<Employee> Employees =
    [
        new Employee
        {
            Id = 101,
            Name = "Rahul",
            Department = "IT"
        },
        new Employee
        {
            Id = 102,
            Name = "Priya",
            Department = "HR"
        }
    ];

    [HttpGet]
    public IActionResult GetEmployees()
    {
        return Ok(Employees);
    }

    [HttpGet("{id:int}")]
    public IActionResult GetEmployeeById(int id)
    {
        var employee = Employees.FirstOrDefault(x => x.Id == id);

        if (employee is null)
        {
            return NotFound(new
            {
                Message = $"Employee with ID {id} was not found."
            });
        }

        return Ok(employee);
    }
}

public class Employee
{
    public int Id { get; set; }

    public string Name { get; set; } = string.Empty;

    public string Department { get; set; } = string.Empty;
}

Make sure your Program.cs registers controllers and maps their routes:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

app.UseHttpsRedirection();

app.MapControllers();

app.Run();

This example uses an in-memory list to keep the focus on request processing. It does not persist data in SQL Server, and the list resets when the application restarts.

Test the API

Run the application and send these requests using Postman or another API client.

Request 1: Get all employees

GET https://localhost:7001/api/employees

Expected response: 200 OK

[
  {
    "id": 101,
    "name": "Rahul",
    "department": "IT"
  },
  {
    "id": 102,
    "name": "Priya",
    "department": "HR"
  }
]

Request 2: Get employee by ID

GET https://localhost:7001/api/employees/101

Expected response: 200 OK

{
  "id": 101,
  "name": "Rahul",
  "department": "IT"
}

Request 3: Get an employee that does not exist

GET https://localhost:7001/api/employees/999

Expected response: 404 Not Found

{
  "message": "Employee with ID 999 was not found."
}

The port number 7001 is only an example. Use the HTTPS URL and port displayed when your own application starts.

11. Important concepts to remember

Before moving forward, understand these concepts:

  • HTTP: Communication protocol used between the client and server.

  • Kestrel: The web server that receives HTTP requests.

  • Middleware: Components that process requests and responses in a pipeline.

  • Routing: Matches an incoming request to an endpoint.

  • Model Binding: Maps request data to action parameters and models.

  • Controller: Handles requests through its action methods.

  • Service: Holds application or business logic.

  • Serialization: Converts objects into a response format such as JSON.

One more important concept is that HTTP APIs are generally designed to be stateless. The server should not rely on remembering the previous request to understand the next one. Each request should carry the information needed to process it, with authentication and other context handled through appropriate mechanisms.

12. Common mistakes beginners should avoid

1. Putting all business logic inside controllers

This makes controllers difficult to maintain as the application grows. Separate business logic into appropriate services.

2. Confusing middleware with controllers

Middleware operates within the request pipeline. Controllers handle requests that match controller endpoints.

3. Thinking routing executes database queries

Routing only identifies the endpoint. Database operations happen in the application logic or data-access layer.

4. Ignoring HTTP status codes

Always return meaningful status codes so that clients can understand whether an operation succeeded or failed.

5. Assuming an API automatically stores data

Returning an object from an API does not save it permanently. Persistence requires an appropriate data-storage mechanism, such as SQL Server.

13. Interview questions

Q1. How does a .NET Core Web API process an incoming request?

An incoming request is received by Kestrel and passed through the ASP.NET Core middleware pipeline. Routing identifies the endpoint, the framework prepares the action parameters, and the controller executes the required logic. The result is then converted into an HTTP response and sent back to the client.

Q2. What is Kestrel?

Kestrel is the cross-platform web server used by ASP.NET Core applications. It receives and handles incoming HTTP connections and passes requests into the application pipeline.

Q3. What is middleware in .NET Core?

Middleware is a component that participates in the HTTP request-response pipeline. It can inspect or modify requests and responses, perform operations, and pass control to the next component.

Q4. What is routing?

Routing matches an incoming HTTP request to an available endpoint based on information such as its URL and HTTP method.

Q5. What is model binding?

Model binding maps data from an HTTP request, such as route values, query strings, and request bodies, to action parameters or models.

Q6. What is the difference between middleware and a controller?

Middleware is used for cross-cutting request-processing operations, such as logging and exception handling. A controller handles requests mapped to its actions and returns application-specific HTTP responses.

Q7. Why do we use JSON in Web APIs?

JSON is a lightweight, widely supported data-interchange format that allows different applications and technologies to exchange structured data.

Conclusion

Now you understand how a .NET Core Web API works internally, from the moment a client sends an HTTP request until the server returns a response.

The complete process can be summarized as:

Client → Kestrel → Middleware → Routing → Model Binding → Controller → Application Logic → HTTP Response → Client

Understanding this lifecycle is important because almost every feature you build in a Web API depends on these concepts.

In the next article, we'll explore one of the most fundamental parts of API development: HTTP Methods – GET, POST, PUT, PATCH, and DELETE. We'll understand when to use each method and how they work through practical C# examples.


Skills Tutorials – Learn • Build • Grow Together

Continue learning with our 30-day .NET Core Web API series.

What is .NET Core Web API? Understanding Its Architecture with a Practical Example

November 3, 2026 5 min read

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:

  1. The HR team needs to retrieve employee information.

  2. The HR team needs to add new employees.

  3. 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:

OperationHTTP endpoint
Get all employeesGET /api/employees
Get employee by IDGET /api/employees/1
Add employeePOST /api/employees
Update employeePUT /api/employees/1
Delete employeeDELETE /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/json

Step 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.json

Each 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 EmployeeManagement

Navigate to the project:

cd EmployeeManagement

Run the application:

dotnet run

The application will start using the configured development URLs.

You can also create the project using Visual Studio:

  1. Open Visual Studio.

  2. Select Create a new project.

  3. Choose ASP.NET Core Web API.

  4. Enter the project name.

  5. Select .NET 8 or .NET 10.

  6. 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/employees

ControllerBase

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/employees

Execute 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:

ApplicationAPI responsibilities
Employee managementEmployees, departments, attendance
E-commerceProducts, carts, orders
BankingAccounts, transactions
HealthcareAppointments, patient records
Learning managementCourses, students, results
CRMCustomers, 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.

http headers in webapi

October 28, 2022 5 min read

Htttp Header:- Http Header is a field of an HTTP request or response that passes additional info about the request or response. For example, a request message can use headers to indicate it's preferred media formats, while a response can use header to indicate the media format of the returned body.


Request Headers:- Headers containing more information about the resource to be fetched or about the client itself or we can say that Http headers that have additional info about the request.Types of Request headers:- 

  • Accept
  • Accept-Encoding
  • Authorization 
  • Origin
  • Referer
  • User-Agent
  • If-Modified Since
  • If-None-Match
  • Cookie
  • Host


Response Headers:- Headers with additional information about the response, like its location or about the server itself (name, version, …). Types of Response Header:-

  • Pragma
  • Server
  • Set-Cookie
  • www-Authentication:- Basic,Bearer Token,Digest etc
  • x-Frame-options
  • Cache-Control
  • Location
  • Expire



Representation Header:- metadata about the resource in the message body (e.g. encoding, media type, etc.). 
OR
Http headers that additional info for both request and response but no relation with the data transmitted in the body . They are formely known as General headers.
  • Content-Type
  • Content-Encoding
  • Content-Length
  • Connection
  • Transfer-Encoding  

Fetch Metadata Request Header:- Headers with metadata about the resource in the message body (e.g. encoding, media type, etc.).

  • Sec-Fetch-Site
  • Sec-Fetch-Mode
  • Sec-Fetch-User
  • Sec-Fetch-Dest  

Note:-The current HTTP/1.1 specification no longer refers to entities, entity headers or entity-body. Some of the fields are now referred to as Representation header fields.


Difference between Accept header and Content-Type header

The Accept header attribute specifies the format of response data which the client expects.


GET /posts HTTP/1.1 

Accept:application/json 


GET /posts/42 HTTP/1.1 

             Accept: application/xml 


Content-Type header attribute specifies the format of the data in the request body so that receiver can parse it into appropriate format.


             ContentType: application/x-www-form-urlencoded

             ContentType: application/multipart/form-data

 



How to upload large files using MVC

October 7, 2022 5 min read




 This is the third post of file upload in mvc ,first was Upload a File In MVC , second was  Upload Multiple File In MVC  and this is Third "Big File Upload In MVC". In ASP.NET default size of uploading a file is 4MB if  we want to upload a file bigger than 4MB size than we need to have some changes in Web.config file. Lets start

Step1:- For creating a file upload application follow this link Upload a File In MVC  or  Upload Multiple File In MVC    

UploadFile.Cshtml

@{
    ViewBag.Title = "UploadFile";
}
<h2>UploadFile</h2>
 
@using (Html.BeginForm("UploadFile", "FileUploading", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        <br />
        <input type="file" id="files" name="files" multiple>
        <input type="submit" value="Upload" />
        @ViewBag.Message
    </div>
}