[英]How to read appsetting.json or App.config using class library? both json and config file are in same class library project
So here is the scenario.所以这是场景。
I am developing some independent tool so i am working with class library.我正在开发一些独立的工具,所以我正在使用 class 库。 Now i want to save some information into same project which is class library.
现在我想将一些信息保存到同一个项目中,即 class 库。 I tried with appsetting.json and App.config but it only works in web project.
我尝试使用 appsetting.json 和 App.config,但它仅适用于 web 项目。
My project looks like below我的项目如下所示
i tried below code我试过下面的代码
var id = System.Configuration.ConfigurationManager.AppSettings["client_id"];
but it is not working.但它不工作。 if i put that same file in web project it is reading successfully.
如果我将同一个文件放入 web 项目,它就会成功读取。
In my case config/json file must be in class library and must read from itself在我的例子中,config/json 文件必须在 class 库中并且必须从自身读取
In a .net core application you need to use Dependency Injection to inject IConfiguration
into your class which will expose your appsettings json values:在 .net 核心应用程序中,您需要使用依赖注入将
IConfiguration
注入到您的 class 中,这将公开您的应用程序设置 json 值:
public class Foo
{
private IConfiguration _config { get; set; }
public Foo(IConfiguration config)
{
this._config = config;
}
}
Now you can read settings:现在您可以阅读设置:
public void DoBar()
{
var id = _config.GetSection("client_id").Value;
}
Just keep chaining .GetSection()
to move down your hierarchy.只需继续链接
.GetSection()
以向下移动您的层次结构。
If you want to have config.json in your class library separately, I recommend that you define your configuration model and implement deserialization for the file.如果你想在你的class库中单独拥有config.json,我建议你定义你的配置model并对该文件进行反序列化。
let's just assume your config.json content is like,让我们假设你的 config.json 内容是这样的,
{ "MyValue1": "Hello", "MyValue2": "World" }
{ "MyValue1": "Hello", "MyValue2": "World" }
you can define Configuration class like below,您可以像下面这样定义配置 class,
using Newtonsoft.Json;
using System;
using System.IO;
namespace Example
{
public class Configuration
{
public string MyValue1 { get; set; }
public string MyValue2 { get; set; }
public static Configuration Load(string path)
{
if (File.Exists(path))
{
var json = File.ReadAllText(path);
return JsonConvert.DeserializeObject<Configuration>(json);
}
else
{
throw new Exception("Configuration file not found!");
}
}
}
}
then you can load your config object from the file and use it like below,然后你可以从文件中加载你的配置 object 并像下面这样使用它,
var config = Configuration.Load(Path.Combine(Directory.GetCurrentDirectory(), "config.json"));
Console.Write(config.MyValue1);
Console.Write(config.MyValue2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.