Visual Studio项目(新格式)中的可选appsettings.local.json [英] Optional appsettings.local.json in (new format) visual studio project
问题描述
我的应用程序使用appsettings.json进行某些设置.如果存在appsettings.local.json,则无论其包含什么设置,它都应覆盖appsettings.json.到目前为止,没问题.
My app uses appsettings.json for some settings. If appsettings.local.json is present, that should override appsettings.json for whatever settings it contains. So far, no problem.
但是我使用git进行版本控制.显然,我不希望其他用户撤消我的本地设置.因此我忽略了appsettings.json.
But I use git for version control. Obviously, I don't want other users pulling down my local settings. So I git ignore appsettings.json.
此外,解决方案中有很多项目.它们共享相同的设置.因此,在解决方案级别上有一个appsettings.json,所有项目都将其包含为链接.
Furthermore, there are a lot of projects in the solution. They share the same settings. So there is an appsettings.json at the solution level, and all the projects include it as a link.
除了一件事,还是不错.为了可用,我必须将appsettings.local.json复制到输出目录.但这不应该在版本控制中.因此,如果有人重新克隆解决方案,他们将没有解决方案.那应该很好,但事实并非如此. VS.说:该文件应该链接,但是到底在哪里?"构建错误.
Still fine, except for one thing. In order to be usable, I have to copy appsettings.local.json over to the output directory. But it shouldn't be in version control. So if someone clones the solution fresh they won't have it. That ought to be fine, but it isn't. VS. says "this file should be linked, but where the heck is it?" build error.
我该如何处理?
推荐答案
对于v2,这非常简单.
With v2 this is dead simple.
- 在项目中添加一个
appsettings.local.json
(它应嵌套在主appsettings.json
文件下面). - 将
appsettings.local.json
添加到您的.gitignore
-
在构造函数内的
startup.cs
中,执行以下操作:
- Add an
appsettings.local.json
to your project (it should nest itself below the mainappsettings.json
file). - Add
appsettings.local.json
to your.gitignore
In your
startup.cs
within the constructor do the following:
public class Startup
{
public IConfigurationRoot Configuration { get; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) //load base settings
.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true) //load local settings
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) //load environment settings
.AddEnvironmentVariables();
Configuration = builder.Build();
}
/*
* rest of your startup.cs
*/
}
这篇关于Visual Studio项目(新格式)中的可选appsettings.local.json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!