Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

i have started a new RESTful project using .NET Core Framework.

I divided my solution in two parts: Framework (set of .NET standard libraries) and Web (RESTful project).

With Framework folder i provide some of library for furthers web project and into one of these i'd like to provide a Configuration class with the generic method T GetAppSetting<T>(string Key).

My question is: how can i get the access to the AppSettings.json file in .NET Standard?

I have found so many example about reading this file, but all these examples read the file into the web project and no-one do this into an extarnal library. I need it to have reusable code for Others project.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
177 views
Welcome To Ask or Share your Answers For Others

1 Answer

As already mentioned in the comments, you really shouldn't do it. Inject a configured IOptions<MyOptions> using dependency injection instead.

However, you can still load a json file as configuration:

IConfiguration configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory()) // Directory where the json files are located
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

// Use configuration as in every web project
var myOptions = configuration.GetSection("MyOptions").Get<MyOptions>();

Make sure to reference the Microsoft.Extensions.Configuration and Microsoft.Extensions.Configuration.Json packages. For more configuration options see the documentation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...