I have an ASP.NET Core application where I would like to hide the console lines that show up when starting the application (as I have my own welcome message)
I found that this answer worked as a solution to my problem as well. My method ended up looking like this:
Console.Write(WelcomeMessage);
ConsOut = Console.Out; //Save the reference to the old out value (The terminal)
Console.SetOut(new StreamWriter(Stream.Null)); //Remove the console output
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseUrls(url)
.UseStartup()
.UseApplicationInsights()
.Build();
host.Start(); //Start the host in a non-blocking way
Console.SetOut(ConsOut); //Put the console output back, after the messages has been written
Console.CancelKeyPress += OnConsoleCancelKeyPress;
var waitHandles = new WaitHandle[] {
CancelTokenSource.Token.WaitHandle
};
WaitHandle.WaitAll(waitHandles); //Wait until the cancel signal has been received
The OnConsoleCancelKeyPress method looks like this:
///
/// This method is meant as an eventhandler to be called when the Console received a cancel signal.
///
///
///
private static void OnConsoleCancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
//Got Ctrl+C from console
Console.WriteLine("Shutting down.");
CancelTokenSource.Cancel();
}
As Start() is a non-blocking call, returning when the WebHost has been started, I can ensure that the messages output while starting the WebHost have already been written by then, and they will not disturb my users anymore (I tested on the machines on which I'd encountered the error in the first place).