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

3
我正在尝试配置我的应用程序的日志记录,以使用指定的路径,但是我在Program.cs文件中尝试访问appsettings.json时似乎无法正常工作。它会抛出错误并且应用程序不会启动。
我找到了这个链接:Read appsettings.json in Main Program.cs并尝试其中的建议,但似乎也没有起作用。
我的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

检查了系统事件日志,似乎这是确切的错误消息:

应用程序'/LM/W3SVC/2/ROOT' 的物理根目录'C:\App\CatalogManager\' 无法加载clr和托管应用程序。CLR工作线程过早退出。

还有这个:

应用程序'/LM/W3SVC/2/ROOT' 的物理根目录'C:\App\CatalogManager\' 遇到意外的托管异常,异常代码= '0xe0434352'。请检查stderr日志以获取更多信息。


请更具体地说明抛出了什么错误。 - Frost2779
你在问题中引用的错误信息已经给了你很多关于如何进一步排除问题的建议。你有没有在将它粘贴到问题中之前实际阅读过那个错误信息?如果你已经按照那些故障排除提示进行了操作,你发现了什么? - user2819245
我在尝试解决问题时添加了更多细节。 - jackfrost5234
你尝试过遵循这个建议吗:“启用记录应用程序进程的标准输出消息”? - alexm
2个回答

5

你可以直接使用 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 ; 
               //...
            );

        });

0

虽然这是一篇旧帖子,但我的问题是没有将appsettings.json文件设置为内容并复制(如果较新)。应用程序找不到我的文件以加载我的设置。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接