204 HTTP Status Code in ASP.NET Core Web API

204 HTTP Status Code in ASP.NET Core Web API

In this article, I will discuss How to Return 204 No Content HTTP Status Code from the ASP.NET Core Web API Controller Action method with Examples. Please read our previous article discussing How to Return 202 Accepted HTTP Status Code in ASP.NET Core Web API with Examples.

204 HTTP Status Code

The 204 HTTP Status Code stands for “No Content”. It indicates that the server has successfully processed the request but has no content to return in the response body. This status is often used in scenarios where a client sends data to the server (like a POST or PUT request), and the server processes the request successfully but does not need to send back any data or body in the response.

For example, if you send a DELETE request to an API to remove a resource, the server might respond with a 204 No Content to indicate that the resource was successfully deleted, but there is no additional information to return. The following are some of the common scenarios where using the 204 status code is appropriate:

  • Successful PUT Requests: When updating a resource on the server and no response body is needed.
  • Successful DELETE Requests: When deleting a resource, and there’s no additional information to send back.
  • POST Requests: When a POST request has been processed, but no additional content is required in the response.
  • HEAD Requests: The 204 status can be used for HEAD requests where the headers are returned without a response body.
How to Return 204 HTTP Status Code in ASP.NET Core Web API?

In ASP.NET Core Web API, returning a 204 Status Code is useful in scenarios where an operation is performed on the server (like a DELETE, PUT, or a POST operation that doesn’t produce a response body) and you want to indicate to the client that the request was successful without sending back any data.

To return a 204 Status Code from an ASP.NET Core Web API controller, we need to use the NoContent method. There is only one overloaded version available for the NoContent method, which does not take any parameters. We can also explicitly return the 204 Status code from the action method in ASP.NET Core Web API using the StatusCode method.

Using NoContent Method to Return 204 Status Code

Let us understand the 204 HTTP Status Code in an ASP.NET Core Web API with an example. First, create the following Employee model class if you have not created it yet, on which we are going to perform the Update and Delete operation.

namespace ReturnTypeAndStatusCodes.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Age { get; set; }
        public string Department { get; set; }
    }
}

In our controller action, we can return a 204 Status Code using the NoContent method. This method belongs to the ControllerBase class, and our API Controller is inherited from this ControllerBase class. So, modify the Employee Controller as follows. Here, we have created two APIs: One is for updating the Employee, and another one is for deleting an employee.

using ReturnTypeAndStatusCodes.Models;
using Microsoft.AspNetCore.Mvc;
namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        //Data Source
        private static List<Employee> Employees = new List<Employee>
        {
            new Employee { Id = 1, Name = "Rakesh", Age = 25, Gender = "Male", Department = "IT" },
            new Employee { Id = 2, Name = "Hina", Age = 26, Gender = "Female", Department = "HR" },
            new Employee { Id = 3, Name = "Suresh", Age = 27, Gender = "Male", Department = "IT" },
        };

        //An example PUT method that uses the 204 No Content response
        //PUT: api/Employee/5
        [HttpPut("{id}")]
        public IActionResult UpdateEmployee(int id, Employee employee)
        {
            if (id != employee.Id)
            {
                return BadRequest();
            }

            var existingEmployee = Employees.FirstOrDefault(emp => emp.Id == id);
            if (existingEmployee == null)
            {
                return NotFound();
            }

            existingEmployee.Name = employee.Name;
            existingEmployee.Age = employee.Age;
            existingEmployee.Gender = employee.Gender;
            existingEmployee.Department = employee.Department;
            // In a real application, here you would update the product in the database

            // If the employee is successfully updated, return a 204 No Content response.
            // This indicates to the client that the request was successful but there is no content to send back.
            return NoContent();
        }

        //An example DELETE method that uses the 204 No Content response
        //DELETE: api/Employee/5
        [HttpDelete("{id}")]
        public IActionResult DeleteEmployee(int id)
        {
            var existingEmployee = Employees.FirstOrDefault(emp => emp.Id == id);
            if (existingEmployee == null)
            {
                return NotFound();
            }
            Employees.Remove(existingEmployee);
            // In a real application, here you would delete the product from the database

            // If the employee is successfully deleted, return a 204 No Content response.
            // This indicates to the client that the request was successful but there is no content to send back.
            return NoContent();
        }
    }
}

In the above example,

  • The UpdateEmployee method attempts to update an employee. If the updation is successful, it returns a 204 No Content response by calling the NoContent() method. If the ID and employee ID do not match, then we return a Bad Request, and if the Employee ID does not exist, then we return a 404 Not Found response.
  • The DeleteEmployee method attempts to delete an employee. If the deletion is successful, it returns a 204 No Content response by calling NoContent(). If the employee cannot be deleted (for example, if it’s not found), a 404 Not Found response is returned instead.
Testing the APIs:

Now, run the application and test the APIs using Postman, Fiddler, Swagger, or .http files. You can test the APIs using Postman as follows: Please change the port number where your application is running:

API1: Returning 204 Status Code After Successful Update Operation

URL: https://localhost:7128/api/Employee/1
Method: PUT
Request Body:

{
  "id": 1,
  "name": "Pranaya",
  "gender": "Make",
  "age": 25,
  "department": "IT"
}

How to Return 204 HTTP Status Code from the ASP.NET Core Web API Controller Action method with Examples

Response Body: The Response body will be empty with 204 HTTP Status Code

How to Return 204 HTTP Status Code in ASP.NET Core Web API

API2: Returning 204 Status Code After Successful Delete Operation

URL: https://localhost:7128/api/Employee/1
Method: DELETE

204 HTTP Status Code in ASP.NET Core Web API

Response Body: The Response body will be empty with a 204 HTTP Status Code.

204 HTTP Status Code

Manual Status Code Setting

Alternatively, you can use the StatusCode method to return a 204 Status Code instead of the NoContent method. So, modify the Employee Controller as follows to use the StatusCode method to return a 204 Status Code:

using ReturnTypeAndStatusCodes.Models;
using Microsoft.AspNetCore.Mvc;
namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        //Data Source
        private static List<Employee> Employees = new List<Employee>
        {
            new Employee { Id = 1, Name = "Rakesh", Age = 25, Gender = "Male", Department = "IT" },
            new Employee { Id = 2, Name = "Hina", Age = 26, Gender = "Female", Department = "HR" },
            new Employee { Id = 3, Name = "Suresh", Age = 27, Gender = "Male", Department = "IT" },
        };

        //An example PUT method that uses the 204 No Content response
        //PUT: api/Employee/5
        [HttpPut("{id}")]
        public IActionResult UpdateEmployee(int id, Employee employee)
        {
            if (id != employee.Id)
            {
                return BadRequest();
            }

            var existingEmployee = Employees.FirstOrDefault(emp => emp.Id == id);
            if (existingEmployee == null)
            {
                return NotFound();
            }

            existingEmployee.Name = employee.Name;
            existingEmployee.Age = employee.Age;
            existingEmployee.Gender = employee.Gender;
            existingEmployee.Department = employee.Department;
            // In a real application, here you would update the product in the database

            // Explicitly return a 204
            return StatusCode(StatusCodes.Status204NoContent); 
        }

        //An example DELETE method that uses the 204 No Content response
        //DELETE: api/Employee/5
        [HttpDelete("{id}")]
        public IActionResult DeleteEmployee(int id)
        {
            var existingEmployee = Employees.FirstOrDefault(emp => emp.Id == id);
            if (existingEmployee == null)
            {
                return NotFound();
            }
            Employees.Remove(existingEmployee);
            // In a real application, here you would delete the product from the database

            // Explicitly return a 204
            return StatusCode(StatusCodes.Status204NoContent);
        }
    }
}

With the above changes in place, run the application, and it should work as expected.

When to Use 204 Status Code in ASP.NET Core Web API?

In ASP.NET Core Web API, you should use the 204 Status Code in the following scenarios:

  • Successful Deletion of a Resource: When a client sends a DELETE request to remove a resource, and there’s no additional content to return.
  • Successful Update with No Content: When a client sends a PUT or PATCH request to update a resource, and no data needs to be returned after the update.
  • Successful Form Submission with No Response: When a client sends a POST request (e.g., via AJAX) that performs an action but does not need to return any content.
  • Successful Batch Operations: When performing batch operations where multiple resources are processed, and no additional content is required in the response.
  • Action Methods with No Content: If an action method processes a request and there is no meaningful content to return, a 204 status code can be used.

In the next article, I will discuss How to Return 301 HTTP Status Code in ASP.NET Core Web API with Examples. In this article, I try to explain How to Return the 204 No Content HTTP Status Code in ASP.NET Core Web API with Examples, and I hope you enjoy this article on “204 No Content HTTP Status Code in the ASP.NET Core Web API”.

Leave a Reply

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