簡體   English   中英

在 Program.cs 中讀取和使用 appsettings.json?

[英]Reading and using appsettings.json in Program.cs?

我正在嘗試為我的應用程序配置日志記錄以使用指定的路徑,但我嘗試訪問 Program.cs 文件中的 appsettings.json 似乎不起作用。 它會引發錯誤並且應用程序無法啟動。

我找到了這個:

在 Main Program.cs 中讀取 appsettings.json

並嘗試了其中的建議,但似乎不起作用。

我的 Program.cs 文件:

public class Program
{
    public static void Main(string[] args)
    {

        var config = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: false)
            .Build();

        LogConfig logConfig = new LogConfig();
        config.GetSection("Config").Bind(logConfig);
        CreateWebHostBuilder(args, logConfig).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args, LogConfig config) =>
        WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging(builder => builder.AddFile(options => {
            options.FileName = "AppLog-"; // The log file prefixes
            options.LogDirectory = config.LoggingPath; // The directory to write the logs
            options.FileSizeLimit = 20 * 1024 * 1024; // The maximum log file size (20MB here)
            options.Extension = "txt"; // The log file extension
            options.Periodicity = PeriodicityOptions.Hourly; // Roll log files hourly instead of daily.
        }))
            .UseStartup<Startup>();
}

和 LogConfig.cs:

public class LogConfig
{
    private string loggingPath;

    public string LoggingPath { get => loggingPath; set => loggingPath = value; }
}

當我嘗試啟動我的應用程序時,我收到以下錯誤消息:

HTTP Error 500.30 - ANCM In-Process Start Failure
Common causes of this issue:
The application failed to start
The application started but then stopped
The application started but threw an exception during startup
Troubleshooting steps:
Check the system event log for error messages
Enable logging the application process' stdout messages
Attach a debugger to the application process and inspect
For more information visit: https://go.microsoft.com/fwlink/?LinkID=2028265

檢查系統事件日志,這似乎是確切的錯誤消息:

具有物理根目錄 'C:\\App\\CatalogManager\\' 的應用程序 '/LM/W3SVC/2/ROOT' 未能加載 clr 和托管應用程序。 CLR 工作線程提前退出

還有這個:

具有物理根目錄 'C:\\App\\CatalogManager\\' 的應用程序 '/LM/W3SVC/2/ROOT' 遇到意外的托管異常,異常代碼 = '0xe0434352'。 請檢查 stderr 日志以獲取更多信息。

您可以使用ConfigureLogging(hostcontext,builder)直接獲取它ConfigureLogging(hostcontext,builder)例如

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
         .UseStartup<Startup>()
        .ConfigureLogging((hostingContext, builder) =>
        {
            var loggingPath = hostingContext.Configuration.GetSection("Config");
            builder.AddFile(options=>
               options.LogDirectory = loggingPath ; 
               //...
            );

        });

舊帖子,但我的問題不是將我的 appsettings.json 文件設置為內​​容並復制(如果更新)。 該應用程序找不到我的文件來加載我的設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM