Skip to content

Instantly share code, notes, and snippets.

@samonzeweb
Created May 17, 2021 12:09
Show Gist options
  • Save samonzeweb/b0793fedbe65fe52b1a09220e816ee76 to your computer and use it in GitHub Desktop.
Save samonzeweb/b0793fedbe65fe52b1a09220e816ee76 to your computer and use it in GitHub Desktop.
ASP.NET Core : open browser on start, and stop server from browser.
// This exemple shows :
// * how to start an app with a free local port
// * how to find urls used and open a brower
// * how to stop the server
//
// Of course it's not production ready, it's a simple howto/reminder.
//
// Some part are come from :
// https://andrewlock.net/how-to-automatically-choose-a-free-port-in-asp-net-core/
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace LocalAndEphemeralAspNetCore
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Program>();
webBuilder.UseUrls("http://127.0.0.1:0;https://127.0.0.1:0");
});
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env,
IHostApplicationLifetime lifetime,
ILogger<Program> logger)
{
lifetime.ApplicationStarted.Register(() =>
{
var url = FindUrl(app.ServerFeatures, logger);
if (url is not null)
{
OpenBrowser(url);
}
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
endpoints.MapGet("/stop", context =>
{
lifetime.StopApplication();
return Task.CompletedTask;
});
});
}
public string FindUrl(IFeatureCollection features, ILogger logger)
{
var addressFeature = features.Get<IServerAddressesFeature>();
string UrlToOpen = null;
foreach (var address in addressFeature.Addresses)
{
logger.LogInformation("Listening on address: " + address);
if (address.StartsWith("https://127.0.0.1:"))
{
UrlToOpen = address;
}
}
return UrlToOpen;
}
public void OpenBrowser(string url)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Process.Start(new ProcessStartInfo("cmd", $"/c start {url}"));
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment