Tuesday, October 29, 2024

Middleware Example, Daily downtime in ASP.NET Core for specific routes

In an ASPNET Core application, there are some routes which need a daily downtime between 17 hrs to 18 hrs. In other words, during that period, no requests can be processed. Any request coming to such routes has to be redirected to another page or a website, say, appliedk.in. How can be implemented it?

To implement a daily downtime in ASP.NET Core for specific routes, you can create middleware that checks the current time. If the request falls within the downtime period, the middleware can redirect the user to another URL (like appliedk.in). Here’s a step-by-step guide to setting this up:

Step 1: Create a Middleware for Downtime Check
Create custom middleware that intercepts requests, checks if they are within the downtime period, and verifies if the route needs to be shut down.

Define Middleware: Add a new middleware class, DowntimeMiddleware.

public class DowntimeMiddleware
{
    private readonly RequestDelegate _next;
    private readonly TimeSpan _downtimeStart = new TimeSpan(17, 0, 0); // 17:00
    private readonly TimeSpan _downtimeEnd = new TimeSpan(18, 0, 0);   // 18:00
    private readonly List<string> _routesWithDowntime;

    public DowntimeMiddleware(RequestDelegate next, List<string> routesWithDowntime)
    {
        _next = next;
        _routesWithDowntime = routesWithDowntime;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var currentTime = DateTime.Now.TimeOfDay;
        var path = context.Request.Path.Value;

        // Check if the current time is within downtime and the route needs downtime
        if (currentTime >= _downtimeStart && currentTime <= _downtimeEnd &&
            _routesWithDowntime.Any(route => path.Contains(route, StringComparison.OrdinalIgnoreCase)))
        {
            // Redirect to the desired URL (e.g., appliedk.in)
            context.Response.Redirect("https://appliedk.in");
            return;
        }

        await _next(context);
    }
}
Step 2: Configure the Middleware in Startup.cs
Register this middleware in the Configure method of your Startup class and provide the routes that require downtime.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        var routesWithDowntime = new List<string>
        {
            "/route1",
            "/route2",
            // Add additional routes here
        };

        // Use the downtime middleware with specific routes
        app.UseMiddleware<DowntimeMiddleware>(routesWithDowntime);

        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
Explanation of the Code
Middleware Logic:
  1. The middleware checks if the current time is between 17:00 and 18:00.
  2. It also checks if the request path matches any of the routes in _routesWithDowntime.
  3. If both conditions are true, it redirects the request to https://appliedk.in.
Route List:
You can specify which routes need downtime by adding them to routesWithDowntime.
Redirection:
context.Response.Redirect("https://appliedk.in"); redirects the request, bypassing further processing.
This solution provides a centralized way to enforce a downtime window for specific routes, ensuring no requests are processed during that time and redirecting users to an alternative page.

No comments:

Post a Comment

Hot Topics