Visual Studio项目(新格式)中的可选appsettings.local.json [英] Optional appsettings.local.json in (new format) visual studio project

查看:281
本文介绍了Visual Studio项目(新格式)中的可选appsettings.local.json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序使用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.

  1. 在项目中添加一个appsettings.local.json(它应嵌套在主appsettings.json文件下面).
  2. appsettings.local.json添加到您的.gitignore
  3. 在构造函数内的startup.cs中,执行以下操作:

  1. Add an appsettings.local.json to your project (it should nest itself below the main appsettings.json file).
  2. Add appsettings.local.json to your .gitignore
  3. 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆