NetCoreUsefullEndpoints–part 7–restart application
In order to do the shutdown, I have added the following extension
public static CancellationTokenSource cts=new ();
public static void MapShutdown(this IEndpointRouteBuilder route, string? corsPolicy = null, string[]? authorization = null)
{
ArgumentNullException.ThrowIfNull(route);
var rh = route.MapPost(“api/usefull/shutdown/”,
(HttpContext httpContext) =>
{
var h= cts.Token.GetHashCode();
cts?.Cancel();
return h;
});rh.AddDefault(corsPolicy, authorization);
}
This code defines a static field called “cts” in the “UsefullExtensions” class. “cts” is an instance of the “CancellationTokenSource” class, which is used to create a CancellationToken that can be used to stop the application gracefully.
The “MapShutdown” method is an extension method for IEndpointRouteBuilder that creates a new endpoint for a POST request to the “api/usefull/shutdown/” URL. When the request is received, the method cancels the “cts” CancellationTokenSource if it is not null, and returns the hash code of the CancellationToken. The method also sets the “corsPolicy” and “authorization” parameters for the endpoint.
You can call with
app.MapUsefullAll();
or with
app.MapShutdown
Anyway , the runAsync should be modified with
await app.RunAsync(UsefullExtensions.UsefullExtensions.cts.Token);
The “RunAsync” method of the “app” object is used to start the application and listen for incoming requests. The method takes a CancellationToken as an argument, which allows the application to be stopped gracefully by cancelling the token. In this case, the token is provided by the “cts” field of the “UsefullExtensions” class. The code uses the “await” keyword to wait for the task returned by “RunAsync” to complete before continuing.
Leave a Reply