Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
ASP.NET Core IHostingStartup that as soon as the site has started makes a request to itself then shuts itself down
using System;
using System.Linq;
using System.Net.Http;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
[assembly: HostingStartup(typeof(SelfShutdown.ShutdownHostingStartup))]
namespace SelfShutdown
public class ShutdownHostingStartup : IHostingStartup
public void Configure(IWebHostBuilder builder)
builder.ConfigureServices(services =>
services.AddTransient<IStartupFilter, ShutdownStartupFilter>();
public class ShutdownStartupFilter : IStartupFilter
private readonly IHostApplicationLifetime _appLifetime;
private readonly IServerAddressesFeature _serverAddresses;
private readonly ILogger<ShutdownStartupFilter> _logger;
public ShutdownStartupFilter(IHostApplicationLifetime appLifetime, IServer server, ILogger<ShutdownStartupFilter> logger)
_appLifetime = appLifetime;
_serverAddresses = server.Features.Get<IServerAddressesFeature>();
_logger = logger;
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
return builder =>
private void OnApplicationStarted()
// Make a request to the site root to force full initialization
var url = _serverAddresses.Addresses.FirstOrDefault(s => s.StartsWith("https://"))
?? _serverAddresses.Addresses.FirstOrDefault(s => s.StartsWith("http://"));
_logger.LogInformation("App startup completed, initiating request to {url}", url);
using var http = new HttpClient();
_logger.LogInformation("Request complete, requesting app shutdown");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment