问题描述
我正在使用 C# 和 Core .NET 构建一个类库.我正在尝试使用 config.json
文件中的配置.以下是该文件的内容:
I am building a class library using C# and Core .NET. I am trying to use configuration from a config.json
file. Here are the contents of that file:
config.json
{
"emailAddress":"[email protected]"
}
为了将 config.json
用于我的配置,我在我的 project.json
中引用了 Microsoft.Framework.ConfigurationModel.Json
代码>文件.在我的代码中,我有以下内容:
In an attempt to use config.json
for my configuration, I'm referencing Microsoft.Framework.ConfigurationModel.Json
in my project.json
file. In my code, I have the following:
MyClass.cs
using Microsoft.Framework.ConfigurationModel;
public class MyClass
{
public string GetEmailAddress()
{
// return ConfigurationManager.AppSettings["emailAddress"]; This is the approach I had been using since .NET 2.0
return ?; // What goes here?
}
}
从 .NET 2.0 开始,我一直在使用 ConfigurationManager.AppSettings["emailAddress"]
.但是,我现在正在尝试通过 IConfiguration
以新的方式学习如何做到这一点.我的问题是,这是一个类库.出于这个原因,我不确定配置文件是如何、在何处或何时加载的.在传统的 .NET 中,我只需要为 ASP.NET 项目命名一个文件 web.config,为其他项目命名一个 app.config 文件.现在,我不确定.我有一个 ASP.NET MVC 6 项目和一个 XUnit 项目.所以,我试图弄清楚如何在这两种情况下使用 config.json
.
Since .NET 2.0, I had been using ConfigurationManager.AppSettings["emailAddress"]
. However, I'm now trying to learn how to do it the new way via IConfiguration
. My problem is, this is a class library. For that reason, I'm not sure how, or where, or when, the configuration file gets loaded. In traditional .NET, I just needed to name a file web.config for ASP.NET projects and app.config for other projects. Now, I'm not sure. I have both an ASP.NET MVC 6 project and an XUnit project. So, I'm trying to figure out how to use config.json
in both of these scenarios.
谢谢!
推荐答案
从未使用过它,但快速搜索使我找到了这个...
Never used it but a quick search lead me to this...
var configuration = new Configuration();
configuration.AddJsonFile("config.json");
var emailAddress = configuration.Get("emailAddress");
也许你可以试试.
这篇关于在 C# 类库中使用 IConfiguration的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!