当您从 Visual Studio (2017) 启动 ASP.NET Core 项目时,它假定工作目录是源代码所在的位置,而不是构建文件实际放置的位置。
这意味着当我运行我的项目时,它会从 C:\Path\To\My\Project\appsettings.json
而不是从 C:\Path\To\My\Project\bin\Debug\appsettings.json
.
我在调试这段代码的时候可以看到是这样的:
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureAppConfiguration((context, config) => {
config.SetBasePath(context.HostingEnvironment.ContentRootPath);
config.AddJsonFile("appsettings.json", true, false);
});
ContentRootPath
指向项目文件夹,而不是构建文件所在的位置。
我可能可以通过在 Project Properties > Debug
中设置 Working Directory
来解决这个问题,但是鉴于我们也在使用配置转换 (SlowCheetah),每个开发人员都会有自己的调试输出构建配置 (bin\Debug[CustomConfiguration]
),并且为一个开发人员更改 .csproj
会破坏所有其他开发人员。
有没有什么方法可以让 ASP.NET Core 从放置构建文件的位置而不是项目文件夹中读取配置文件,而无需更改 Working Directory
,但仍然适用于多个“构建配置”?
最佳答案
如果我对问题的理解正确,每个开发人员的用户名都有不同的输出文件夹。所以,如果你编这样的东西,
var debug = string.Empty;
#if DEBUG
debug = "Debug";
#else
debug = "Release";
#endif
var userNameVariable = System.Environment.GetEnvironmentVariable("USER");
debug += $"[{userNameVariable}]";
var path = System.IO.Path.Combine(env.ContentRootPath, "bin", debug);
var builder = new ConfigurationBuilder()
.SetBasePath(path) //env.ContentRootPath
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
我已经在 Mac OS 上测试过了,结果是
/Users/johndoe/Documents/Temp/contentasp/bin/Debug[johndoe]
其他解决方案。
在 visual studio 中,您有预构建和后构建脚本。在 Visual Studio 中,您可以获得 OutputFolder 并将路径设置到预构建脚本的环境变量中。例如:
powershell.exe -ExecutionPolicy 绕过 -File "$(ProjectDir)outputscript.ps1"-OutputFolder $(OutputPath)
并且在 powershell 脚本中 (outputscript.ps1
)
Param(
[Parameter(Mandatory = $true, Position = 1)]
[string]$OutputFolder
)
$env:OutputFolder = $OutputFolder
你可以在启动时获得值(value)
var outputFolder = System.Environment.GetEnvironmentVariable("OutputFolder");
var builder = new ConfigurationBuilder()
.SetBasePath(outputFolder) //env.ContentRootPath
关于c# - 从 Visual Studio 启动 ASP.NET Core 不是从构建文件夹启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56888572/