簡體   English   中英

ASP.NET Core 應用程序不會從輸出目錄中讀取 appsettings.json,而是從項目一中讀取

[英]ASP.NET Core app does not read appsettings.json from output directory, but from the project one

在 ASP.NET Core 中,我遇到了一個我不明白的行為。

在使用控制台應用程序以讀取配置文件時,我通過以下方式將其復制到輸出目錄:

 <ItemGroup>
      <Content Include="mysettings.json">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </Content>
    </ItemGroup>

否則,如果我只使用文件名而不是完整路徑,我會得到FileNotFoundException 這樣我可以從其他項目導入文件(例如另一個設置 jsons)並且它工作正常。

到現在為止還挺好。

但是,在 ASP.NET Core 中(我在一個帶有 ASP.NET Core 后端的 Blazor Web 程序集項目上工作更具體)當我運行服務器項目時,設置不是從輸出目錄中讀取的,而是從項目目錄中讀取的。 因此,我在嘗試從解決方案中的另一個項目讀取設置文件時遇到錯誤,因為應用程序在項目文件夾而不是輸出文件夾中查找它。

我不確定它是否相關,但Directory.GetCurrentDirectory()顯示/BlazorApp/Server而我寧願期待/BlazorApp/Server/bin/Debug/netcoreapp3.1

這是 ASP.NET Core 中的預期行為嗎? 如果是這樣,我如何處理來自其他項目的文件? 我想避免在多個地方手動更新設置。

提前致謝

要訪問“/BlazorApp/Server/bin/Debug/netcoreapp3.1”,您需要使用(在System命名空間中) AppDomain.CurrentDomain.BaseDirectory

您還可以在啟動時添加另一個配置文件(或替換默認配置),如下所示:

public class Program
{
    public static void Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory()) // This is the line you would change if your configuration files were somewhere else
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)


            .AddJsonFile("myappconfig.json", optional: false, reloadOnChange: false) // And this is the line you would add to reference a second configuration file other than appSettings.json
            .Build();

        BuildWebHost(args, configuration).Run();
    }

    public static IWebHost BuildWebHost(string[] args, IConfiguration config) =>
        WebHost.CreateDefaultBuilder(args)
            .UseConfiguration(config)
            .UseStartup<Startup>()
            .Build();
}`

暫無
暫無

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

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