gpt4 book ai didi

c# - 隐藏 ASP.NET Core WebHost 消息

转载 作者:行者123 更新时间:2023-11-30 17:31:46 25 4
gpt4 key购买 nike

我有一个 ASP.NET Core 应用程序,我想在其中隐藏启动应用程序时显示的控制台行(因为我有自己的欢迎消息)

Hosting environment: Development
Content root path: path\to\my\executable
Now listening on: http://localhost:portnumber
Application started. Press Ctrl+C to shut down.

我尝试了一种解决方案,我将 Console.Out 设置为空流,然后在我想写东西时将其设置回去。它在我的开发 PC 上运行良好,但我发现该问题出现在其他 PC 上。

    Console.Write(WelcomeMessage);
ConsOut = Console.Out; //Save the reference to the old out value (The terminal)
Console.SetOut(new StreamWriter(Stream.Null)); //Hack out the console
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseUrls(url)
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();

我对这个解决方案不满意,因为它看起来像是一个 hack,而且不能始终如一地工作。

来自 How to turn off the logging done by the ASP.NET core framework ,我发现您可以在 Startup.cs 类的 Configure() 方法中禁用自动日志记录系统,所以我相信这与我正在寻找的类似,我只是不知道如何删除托管消息。

编辑:我注意到我的问题与 Asp.Net Core API disable startup complete message 相同.但是对于想隐藏启动信息,又想自己写控制台信息的问题一直没有得到满意的答复。

最佳答案

我发现 this answer也可以解决我的问题。我的方法最终看起来像这样:

     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<Startup>()
.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

OnConsoleCancelKeyPress 方法如下所示:

    /// <summary>
/// This method is meant as an eventhandler to be called when the Console received a cancel signal.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void OnConsoleCancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
//Got Ctrl+C from console
Console.WriteLine("Shutting down.");
CancelTokenSource.Cancel();
}

由于 Start() 是一个非阻塞调用,当 WebHost 启动时返回,我可以确保启动 WebHost 时输出的消息已经写入,它们不会再打扰我的用户(我在我一开始遇到错误的机器上进行了测试)。

关于c# - 隐藏 ASP.NET Core WebHost 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47458709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com