503 HTTP Status Code in ASP.NET Core Web API

503 HTTP Status Code in ASP.NET Core Web API

In this article, I will discuss How to Return 503 Service Unavailable HTTP Status Code in ASP.NET Core Web API Application with Examples. Please read our previous article discussing How to Return 501 Not Implemented HTTP Status Code in ASP.NET Core Web API with Examples.

503 HTTP Status Code

The HTTP 503 Status Code, known as “Service Unavailable,” is an error response code indicating that the server is not ready to handle the request. This unavailability can be due to several reasons, such as the server being overloaded with requests, undergoing maintenance, or experiencing temporary technical issues.

Key aspects of the 503 Status Code include:

  • Temporary Nature: Unlike permanent error codes, a 503 error suggests a temporary condition. The server is essentially communicating that it is currently unable to process the request but might be able to at a later time.
  • Retry-After Header: Servers can optionally include a Retry-After header in the 503 Response to indicate how long the service is expected to be unavailable. Clients can use this information to decide when to retry the request.
  • Impact on SEO: For websites, 503 errors can negatively affect search engine rankings if search engines interpret the site as unreliable. It’s crucial for webmasters to resolve these issues quickly.
  • Best Practices for Handling: When a server is intentionally taken down for maintenance, it’s best practice to use the 503 Status Code to inform clients and possibly provide a Retry-After header. This approach is preferable to shutting down the server without any response, as it informs clients that the unavailability is temporary.
  • User Experience: For end-users encountering a 503 error, the recommended action is to wait and retry later. Users can also check the website’s social media channels or status page for updates on the service.
How to Return 503 HTTP Status Code in ASP.NET Core Web API

A 503 HTTP Status Code indicates that the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. To demonstrate how to return a 503 Status Code in an ASP.NET Core Web API, we’ll create a simple example. This involves configuring a middleware that checks for a specific condition (e.g., a flag indicating maintenance mode) and, based on that, either allows the request to proceed or returns a 503 Service Unavailable response.

Configure appsettings.json

We need to add a key in the appsettings.json file, which will tell whether the service is under maintenance. So, add the following key in the appsettings.json file and set its value to true:

"IsApplicationUnderMaintenance": "true"
Implement a Custom Middleware Component:

Create a new class file named MaintenanceMiddleware.cs, then copy and paste the following code. This middleware will intercept requests and return a 503 Status Code if the application is under maintenance. The following MaintenanceMiddleware class checks if the application is under maintenance and, if so, returns a 503 Service Unavailable response.

using System.Text.Json;

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

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

        public async Task Invoke(HttpContext httpContext, IConfiguration configuration)
        {
            // Implement your logic here
            // Read a Configuration Value which indicates whether the server Is Under Maintenance 
            bool IsUnderMaintenance = Convert.ToBoolean(configuration["IsApplicationUnderMaintenance"]);

            if (IsUnderMaintenance)
            {
                httpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
                httpContext.Response.ContentType = "application/json";
                httpContext.Response.Headers.Add("Retry-After", "120");
                var customResponse = new
                {
                    Code = 503,
                    Message = "Service is under maintenance. Please try again later.",
                };

                var responseJson = JsonSerializer.Serialize(customResponse);

                await httpContext.Response.WriteAsync(responseJson);
            }
            else
            {
                await _next(httpContext);
            }
        }
    }
}
In the above example,
  • _next: A field of type RequestDelegate. This delegate represents the next middleware in the pipeline. It’s stored in a private read-only field, ensuring it’s only set once during construction and cannot be changed.
  • Constructor: The constructor takes a RequestDelegate called next as a parameter. This delegate points to the next middleware in the application’s request pipeline. The passed-in delegate is assigned to the _next field, allowing this middleware to call the next one in the pipeline.
  • Invoke: This method is required for a class to function as middleware in ASP.NET Core. It must take an HttpContext as a parameter and return a Task. The HttpContext represents information about the current HTTP request and provides methods to deal with the response.
  • Inside the Invoke method, we are reading the IsApplicationUnderMaintenance configuration key value from the appsettings.json file. If its value is true, then we are creating a 503 custom error message and returning that to the client. Otherwise, we will proceed with the normal execution flow.
Register the Middleware

In the Program.cs file, we need to register the middleware component as follows. This ensures it’s part of the request processing pipeline. This should be the first middleware component in the request processing pipeline.

app.UseMiddleware<MaintenanceMiddleware>();

Controller:

Next, modify the Sample Controller as follows:

using Microsoft.AspNetCore.Mvc;
namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SampleController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetResource()
        {
            return Ok("Service is Available");
        }
    }
}

Now, run the application and make a request to any endpoint. You should receive a 503 Service Unavailable response with the message “Service is under maintenance. Please try again later.” as shown in the below image:

How to Return 503 Service Unavailable HTTP Status Code in ASP.NET Core Web API Application with Examples

When Should We Use 503 HTTP Status Code in ASP.NET Core Web API?

Here are several scenarios when you might use the 503 Status Code in your ASP.NET Core Web API:

  • Maintenance Windows: If you have scheduled maintenance for your server or the underlying infrastructure, you can use the 503 Status Code to inform clients that the service is temporarily unavailable. It’s a good practice also to return a Retry-After header indicating how long the service is expected to be unavailable.
  • Overloaded Server: If your server is experiencing an unusually high volume of requests that it cannot handle efficiently, returning a 503 status can inform clients to retry their requests after some time. This can help in mitigating the load and preventing the server from crashing.
  • Dependency Outages: If your API relies on external services or databases that are temporarily unavailable, you might use a 503 status to indicate that your API cannot fulfil requests due to these external dependencies being down.

In the next article, I will discuss How to Return 504 Gateway Timeout HTTP Status Code in ASP.NET Core Web API with Examples. In this article, I try to explain How to Return 503 Service Unavailable HTTP Status Code in ASP.NET Core Web API with Examples, and I hope you enjoy this article “503 Service Unavailable HTTP Status Code in ASP.NET Core Web API”.

Leave a Reply

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