NetCoreUsefullEndpoints-part 9- adding endpoints for shutdown
In my NuGet NetCoreUsefullEndpoints package I want to can shutdown the application . Could be hard way, like calling Environment.Exit or the easy way , like calling a cancellation token. Also, what should happen with all the requests that are coming ? ( And I do not want to mention long running tasks – I do not found a useful registration / un-registration for those)
So I come with the following implementation for forced exit
//IEndpointRouteBuilder
var rhForced = route.MapPost(“api/usefull/shutdownForced/{id:int}”,
(int id) =>
{
Environment.Exit(id);
});
For the shutdown that is requested , I come with 3 modifications:
1.In Program.cs , I put a Middleware for not serving the HTTP
builder.Services.AddSingleton<MiddlewareShutdown>();
app.UseMiddleware<MiddlewareShutdown>();
await app.RunAsync(UsefullExtensions.UsefullExtensions.cts.Token);
2. Register the routes in order to use the cancellation token
//IEndpointRouteBuilder
var rhSec = route.MapPost(“api/usefull/shutdownAfter/{seconds}”,
(HttpContext httpContext, int seconds) =>
{
RequestedShutdownAt = DateTime.UtcNow;
var h = cts.Token.GetHashCode();
cts?.CancelAfter(Math.Abs(seconds)*1000);
return h;});
3. Use a middleware to return 418 Status Code if the application is shutting down
public class MiddlewareShutdown : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
if (UsefullExtensions.RequestedShutdownAt != null)
{
context.Response.StatusCode = 418;
await context.Response.WriteAsync(“Service is stopping at ” + UsefullExtensions.RequestedShutdownAt!.Value.ToString(“s”));
return;
}
await next(context);
return;
}
}
And with those you can shutdown gracefully any ASP.NET Core application ( without long running tasks!)
Leave a Reply