asp.net-core - 如何在 .Net Core 中将 App.config 更改为 json 配置文件

标签 asp.net-core asp.net-core-mvc .net-core asp.net-core-1.0 .net-core-rc2

我的项目使用 App.config 来读取配置属性。例子: ConfigurationManager.AppSettings["MaxThreads"] 你知道我可以用来从 json 读取配置的库吗?谢谢。

最佳答案

ConfigurationManager静态类在 ASP.NET Core 中通常不可用。相反,您应该使用新的 ConfigurationBuilder系统和强类型配置。

例如,默认情况下,您的Startup 中会建立一个配置。使用类似于以下内容的类:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}

这将从 appsettings.json 加载配置。文件并将 key 附加到配置根目录。如果您有如下的 appsettings 文件:
{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Debug",
    "System": "Information",
    "Microsoft": "Information"
    }
  },
  "ThreadSettings" : {
     "MaxThreads" : 4
  }
}

然后你可以创建一个强类型ThreadSettings类似于以下的类:

public class ThreadSettings
{
    public int MaxThreads {get; set;}
}

最后,您可以通过添加 Configure 将此强类型设置类绑定(bind)到您的配置。方法到您的ConfigureServices方法。

using Microsoft.Extensions.Configuration;
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<ThreadSettings>(Configuration.GetSection("ThreadSettings"));
}

然后,您可以通过将其注入(inject)构造函数来从任何其他地方注入(inject)和访问您的设置类。例如:

public class MyFatController
{
    private readonly int _maxThreads;
    public MyFatController(ThreadSettings settings)
    {
        maxThreads = settings.MaxThreads;
    }
}

最后,如果你真的需要访问底层配置,你也可以在 ConfigureServices 中注入(inject)它。使其在您的类(class)中可用。

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton(Configuration);
}

您可以在 docs 上阅读有关配置的更多信息。或 various blogs

关于asp.net-core - 如何在 .Net Core 中将 App.config 更改为 json 配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38614964/

相关文章:

asp.net-core - 使用 UseJwtBearerAuthentication 中间件自定义 401 和 403 响应模型

asp.net - 为什么 ASP.NET Core 将波斯语(或阿拉伯语)文本转换为 View 中的字符引用 (&#xhhhh;)

c# - 在测试项目中使用 ASP.NET Core 的 ConfigurationBuilder

c# - 如何在不写入磁盘或在内存中加载完整文件的情况下压缩文件并通过 HTTP 发送?

rest - JWT 和一次性 token ?

angular - 使用 ASP.NET Core REST API 在 SPA (Angular 2) 中进行社交注册

.net - Blazor United 会取代 WASM 和服务器吗

c# - 使用 sonarqube 跨多个项目文件进行代码覆盖率分析

docker - .net sdk 在 alpine linux 上

.net - 使用 UseGoogleAuthentication