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 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 HTTP Status Code in ASP.NET Core Web API with Examples.

204 HTTP Status Code

The 204 No Content HTTP Status Code is a success status response code indicating that the request has succeeded, but the client doesn’t need to navigate away from its current page. This status code is commonly used in situations where the request is successful, and the response does not return any content, such as when an operation has been processed successfully on the server, but there is no additional content to send in the response payload.

Use cases for a 204 No Content response might include:

  • AJAX Calls: In web development, making asynchronous requests where the client might only need to know that the action was successful without requiring any data to be returned. For instance, after submitting a form via AJAX, the page does not need to be refreshed or updated with new content.
  • APIs: For RESTful APIs, when performing operations like DELETE, the server successfully processes the request but does not need to return any entity-body.
  • Signal Success: Indicating to the client that their request was processed successfully, but there’s no new information to send back.

The key characteristic of the 204 No Content Status Code is that it allows the client to remain on the same page, making it useful for web applications that require smooth, uninterrupted user experiences. Unlike 200 OK, which typically indicates that a response contains a payload, 204 explicitly tells the client that the response contains no data and, thus, the client should not expect any content.

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

Returning a 204 HTTP status code in an ASP.NET Core Web API indicates the request was successful, but there is no content to return. This response is typically used for APIs where an action has been successfully processed, but the client does not need to navigate away from its current page or refresh its current state.

In the context of an 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 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 NoContent(). 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

Returning 204 Status Code Directly

Alternatively, you can return a StatusCode result directly if you want to be more explicit or if you need to return a 204 Status Code in scenarios not covered by the NoContent method. So, modify the Employee Controller as follows:

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.

Best Practices and Considerations
  • Use Case: The 204 No Content status is best used for operations that do not need to return any data. Common use cases include DELETE operations, where the client does not need any further information about the deleted resource, or POST/PUT operations, where the result does not need to be communicated back to the client.
  • Client Handling: Ensure that your client-side application correctly handles a 204 response, especially since no data will be returned. This might mean simply acknowledging the success of the operation and updating the UI accordingly.
  • Error Handling: If your operation fails (for example, if the item to be deleted or updated is not found), return an appropriate error status code (such as 404 Not Found) along with any relevant error messages.
When to Use 204 Status Code in ASP.NET Core Web API?

The HTTP 204 No Content Status Code is useful in scenarios where the client does not need to update its existing view or where no additional information needs to be provided as a response to the request. Here are some common scenarios where using the 204 status code is appropriate:

  • Update Operations: When a client sends a request to update a resource (e.g., PUT, PATCH requests) and the operation is successful, but there’s no need to return the updated resource or any message in the body of the response. The 204 Status Code effectively communicates that the request was successful without providing additional data.
  • Delete Operations: After a client sends a request to delete a resource and the server successfully processes this request, a 204 Status Code can be returned to indicate that the operation was successful and that there’s no content to return, as the resource is no longer available.
  • Actions Without a Response Body: For any action that the server successfully processes where returning data is unnecessary or irrelevant. For example, submitting a form where the server doesn’t need to return data, only to acknowledge that the submission was successful.

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 *