404 HTTP Status Code in ASP.NET Core Web API

404 HTTP Status Code in ASP.NET Core Web API

In this article, I will discuss How to Return the 404 Not Found HTTP Status Code in the ASP.NET Core Web API Application with Examples. Please read our previous article discussing How to Return 403 HTTP Status Code in ASP.NET Core Web API with Examples.

404 HTTP Status Code

The 404 “Not Found” HTTP status code is an error message that indicates the server could not find the requested resource. This status code is a standard response in the HTTP protocol, signaling to the client (typically a web browser) that the URL they have requested does not exist on the server. It’s one of the most recognizable and common errors encountered on the internet.

Common Causes of a 404 Error:
  • Incorrect URL: The most common cause is simply that the URL was typed incorrectly into the browser’s address bar.
  • Moved or Deleted Content: If a webpage or resource was moved to a different URL without proper redirection or if it was deleted, a 404 error will occur when attempting to access it.
  • Broken or Dead Links: Links on a website that points to resources that have been moved or removed will lead to a 404 error when clicked.
  • Domain Name Issues: If the domain name cannot be resolved to the correct server or if it’s not properly configured, a 404 error might occur.
  • Server Configuration Issues: Incorrect configuration on the server side can lead to resources not being found, even if they exist.
Handling a 404 Error:
  • For Web Users: If you encounter a 404 error, double-check the URL for typos. You can also try navigating to the homepage of the website and searching for the content you’re looking for.
  • For Webmasters and Developers: It’s important to regularly check for broken links on your website and fix them. Implementing meaningful 404 error pages that guide users to a working part of your site can improve user experience. Additionally, setting up proper redirects for content that has moved can prevent 404 errors from occurring.
How to Return 404 HTTP Status Code in ASP.NET Core Web API?

To return a 404 HTTP status code in an ASP.NET Core Web API, you typically use the NotFound method in your controller actions. The NotFound method is part of the ControllerBase class, which your controllers inherit from when creating a Web API. This method generates a response with a 404 Status Code, indicating that the requested resource could not be found. Here is a step-by-step guide on how to implement this:

  • Define Your Controller: Ensure your controller inherits from ControllerBase or a similar base class that provides the necessary action result methods.
  • Implement the Action: In the action where you want to return a 404 status, check the condition under which the resource would not be found. If the condition is met, return the NotFound result.
  • Use NotFound Method: The NotFound method can be called with no arguments or with an object that provides additional details about the error.

Here’s a simple example of a controller action that tries to find a resource by its ID and returns a 404 Status Code if the resource cannot be found:

using Microsoft.AspNetCore.Mvc;

namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [HttpGet("{id}")]
        public IActionResult GetResource(int id)
        {
            var resource = FindResourceById(id);

            if (resource == null)
            {
                // Resource not found, return 404
                return NotFound();
            }

            // Resource found, return it with 200 OK status
            return Ok(resource);
        }

        // Mock method to simulate resource lookup
        private object FindResourceById(int id)
        {
            // Assume this method returns null if the resource is not found
            // In a real application, you would query your database or data source here
            return null;
        }
    }
}
Response:

Now, run the application and access the above endpoint, and you should get the following 404 Not Found response:

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

Returning 404 with Custom Error Message:

You can also pass an object to the NotFound method that includes details about why the resource was not found. For a better understanding, please modify the controller as follows:

using Microsoft.AspNetCore.Mvc;

namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [HttpGet("{id}")]
        public IActionResult GetResource(int id)
        {
            var resource = FindResourceById(id);

            if (resource == null)
            {
                // Resource not found, return 404
                var customResponse = new { message = $"No Employee Found with the Id: {id}" };
                return NotFound(customResponse);
            }

            // Resource found, return it with 200 OK status
            return Ok(resource);
        }

        // Mock method to simulate resource lookup
        private object FindResourceById(int id)
        {
            // Assume this method returns null if the resource is not found
            // In a real application, you would query your database or data source here
            return null;
        }
    }
}
Response:

Returning 404 with Custom Error Message

Manually Returning 404 Status Code in ASP.NET Core Web API:

We need to use the StatusCode method, and to this method, we need to pass the 404 Status Code and optional object that we want to return. For a better understanding, please modify the controller as follows:

using Microsoft.AspNetCore.Mvc;

namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [HttpGet("{id}")]
        public IActionResult GetResource(int id)
        {
            var resource = FindResourceById(id);

            if (resource == null)
            {
                // Resource not found, return 404
                var customResponse = new { message = $"No Employee Found with the Id: {id}" };
                return StatusCode(StatusCodes.Status404NotFound, customResponse);
            }

            // Resource found, return it with 200 OK status
            return Ok(resource);
        }

        // Mock method to simulate resource lookup
        private object FindResourceById(int id)
        {
            // Assume this method returns null if the resource is not found
            // In a real application, you would query your database or data source here
            return null;
        }
    }
}
Response:

Manually Returning 404 Status Code in ASP.NET Core Web API

Points to Remember
  • Use NotFound for 404 Status: The NotFound method should be used whenever the requested resource is not found. It automatically sets the response status code to 404.
  • Returning Details: Optionally, you can pass an object to NotFound that includes details about why the resource was not found, which can be helpful for debugging or informing the client.
Endpoint Does Not Exist Example in ASP.NET Core Web API

In ASP.NET Core Web API, when you attempt to access an endpoint that does not exist, it means that the route you are trying to reach is not defined in the application. This can happen for a variety of reasons, such as typos in the URL, forgetting to define the route in your controller, or the route being removed but still being referenced elsewhere. By default, ASP.NET Core will respond with a 404 Status Code (Not Found) for such requests.

To handle these scenarios and to provide a custom response when an endpoint does not exist, you can use middleware to catch and respond to these cases.

Create a Middleware Class

First, you need to create a middleware class that checks if the HTTP response is a 404 and, if so, modifies the response accordingly. So, create a class file named NotFoundCustomMiddleware.cs and then copy and paste the following code:

using System.Text.Json;

namespace ReturnTypeAndStatusCodes.Models
{
    public class NotFoundCustomMiddleware
    {
        private readonly RequestDelegate _next;

        public NotFoundCustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            await _next(context);

            if (context.Response.StatusCode == 404 && !context.Response.HasStarted)
            {
                context.Response.ContentType = "application/json";
                var customResponse = new
                {
                    Code = 404,
                    Message = "Endpoint does not exist"
                };

                var responseJson = JsonSerializer.Serialize(customResponse);

                await context.Response.WriteAsync(responseJson);
            }
        }
    }
}
The class is composed of the following key components:
  • Private Field (private readonly RequestDelegate _next): This field holds the RequestDelegate passed to the constructor. It’s used to invoke the next middleware in the pipeline.
  • Constructor (public NotFoundCustomMiddleware(RequestDelegate next)): The constructor accepts a RequestDelegate named next. This delegate represents the next middleware in the pipeline. The constructor stores this delegate in a private field for later use.
  • Invoke Method (public async Task Invoke(HttpContext context)): This is the method that gets called when the middleware is executed. It takes an HttpContext object as a parameter, which provides information about the current HTTP request and response.
Functionality:

The Invoke method performs the following actions:

  • Execution of Next Middleware: Initially, it calls the next middleware in the pipeline by awaiting _next(context). This allows the request to proceed through the remaining middleware (and potentially reach a controller action if the route exists).
  • Check Response Status Code: After the next middleware executes, it checks the response’s status code using context.Response.StatusCode. If the status code is 404, which signifies that no endpoint matched the request, it proceeds to modify the response.
  • Modify Response for 404 Status Code: If the response status code is 404, and the response has not already started (!context.Response.HasStarted), the middleware sets the ContentType of the response to application/json. Then, it creates a new response object with a custom message indicating that the endpoint does not exist. This object is serialized to JSON and written to the response body using await context.Response.WriteAsync(responseJson).
Register the Middleware

After creating the middleware, you need to register it in the Program class. It’s important to add it at the right point in the middleware pipeline to ensure that it catches 404 responses correctly.

app.UseMiddleware<NotFoundCustomMiddleware>();

This middleware checks the status code after all other middleware has executed (assuming none have produced a response). If the status code is 404, it modifies the response to include a custom JSON message indicating that the endpoint does not exist.

Testing:

Now, try to access an endpoint that does not exist, and you should get the following response:

How to Return a 404 Not Found HTTP Status Code in ASP.NET Core Web API with Examples

When Should We Return 404 HTTP Status Code in ASP.NET Core Web API?

In ASP.NET Core Web API, the 404 HTTP status code is used to indicate that the server could not find the requested resource. This status code is particularly useful in RESTful APIs to communicate to the client that the endpoint they are trying to access does not exist or that a specific resource identified by the client (for example, through a URI) cannot be found. Here are several scenarios in which returning a 404 Status Code is appropriate:

  • Resource Not Found: The most common scenario to return a 404 response is when a requested resource does not exist. For example, if your API has an endpoint to get a user by ID (GET /api/users/{id}), and there is no user with the provided ID, the API should return a 404 Status Code.
  • Endpoint Does Not Exist: If a client sends a request to an endpoint that does not exist, the API should return a 404 Status Code. This helps the client understand that the URI they requested is not recognized by the server.

In the next article, I will discuss How to Return the 405 Method Not Allowed HTTP Status Code in ASP.NET Core Web API with Examples. In this article, I try to explain How to Return a 404 Not Found HTTP Status Code in ASP.NET Core Web API with Examples, and I hope you enjoy this article on “404 Not Found HTTP Status Code in the ASP.NET Core Web API”.

Leave a Reply

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