c# - 从 .NET 4.5.2 项目访问 appsettings.json

标签 c# asp.net-core

我有两个项目,一个 1.1.0 ASP.NET Core 项目和一个对 4.5.2 项目的引用。

我想从 appsettings.json 文件获取值到我的 4.5.2 项目。 appsettings.json 文件在核心项目中。

在我的 4.5.2 项目中试过这个,但没有成功:

var mailServer = ConfigurationManager.AppSettings["MailServer"];

如何访问我的 4.5.2 项目中的值?

最佳答案

ConfigurationManager 使用基于 XML 的配置文件,这些文件具有 specific format并且不知道如何读取自定义 JSON 文件。

因为您也将 appsettings.json 用于 ASP.NET Core 项目,您可以将依赖项添加到 Microsoft.Extensions.ConfigurationMicrosoft.Extensions.Configuration.Json使用“.NET Core 方法”打包和读取设置:

var builder = new ConfigurationBuilder()
              .AddJsonFile(@"<path to appsettings.json>");

var configuration = builder.Build();
//  configuration["MailServer"]

当然,由于 appsettings.json 是一个简单的 JSON 文件,您始终可以使用任何 JSON 提供程序直接反序列化。

关于c# - 从 .NET 4.5.2 项目访问 appsettings.json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46054019/

相关文章:

c# - C# : operator '<' cannot be applied to operands of type 'T' and 'T' 中的比较

razor - 在没有 MVC 的情况下使用 ASP.NET 5(简单的 Web 表单/网页)

缓存过期后 Azure 功能标志不会更新

c# - ASP.NET 5 类库可以面向 .NET 3.5 吗?

c# - .NET Framework 和兼容性

c# - 构建远距离查询数据库和程序的最佳方式

c# - 精确匹配单词,如果前面有特殊符号则不匹配

c# - DotNetZip - 无法访问已关闭的流

jquery - Bower在VS2015.3下载错误版本

javascript - 我应该在哪里包含 View 组件的脚本?