diff --git a/Endpoint/Middleware/MaintenanceModeMiddleware.cs b/Endpoint/Middleware/MaintenanceModeMiddleware.cs new file mode 100644 index 0000000..2bd5d3b --- /dev/null +++ b/Endpoint/Middleware/MaintenanceModeMiddleware.cs @@ -0,0 +1,39 @@ +using Microsoft.AspNetCore.Http; +using Mirea.Api.Endpoint.Common.Attributes; +using Mirea.Api.Endpoint.Common.Interfaces; +using System.Threading.Tasks; + +namespace Mirea.Api.Endpoint.Middleware; + +public class MaintenanceModeMiddleware(RequestDelegate next, IMaintenanceModeService maintenanceModeService, IMaintenanceModeNotConfigureService maintenanceModeNotConfigureService) +{ + private static bool IsIgnoreMaintenanceMode(HttpContext context) + { + var endpoint = context.GetEndpoint(); + return endpoint?.Metadata.GetMetadata() != null; + } + + public async Task Invoke(HttpContext context) + { + if (!maintenanceModeService.IsMaintenanceMode && !maintenanceModeNotConfigureService.IsMaintenanceMode || IsIgnoreMaintenanceMode(context)) + await next(context); + else + { + + context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; + context.Response.ContentType = "plain/text"; + + string error; + if (maintenanceModeService.IsMaintenanceMode) + { + context.Response.Headers.RetryAfter = "600"; + error = "The service is currently undergoing maintenance. Please try again later."; + } + else + error = + "The service is currently not configured. Go to the setup page if you are an administrator or try again later."; + + await context.Response.WriteAsync(error); + } + } +} \ No newline at end of file diff --git a/Endpoint/Program.cs b/Endpoint/Program.cs index a238bbf..340478c 100644 --- a/Endpoint/Program.cs +++ b/Endpoint/Program.cs @@ -13,6 +13,7 @@ using Mirea.Api.Endpoint.Common.Services; using Mirea.Api.Endpoint.Configuration; using Mirea.Api.Endpoint.Configuration.General; using Mirea.Api.Endpoint.Configuration.Swagger; +using Mirea.Api.Endpoint.Middleware; using Swashbuckle.AspNetCore.SwaggerGen; using System; using System.Collections; @@ -118,6 +119,7 @@ public class Program } }); } + app.UseMiddleware(); app.UseHttpsRedirection();