SoFunction
Updated on 2025-03-09

How to use configuration files in core web

Preface

Recently, I am studying the application porting to Linux, and the .net core came out, so I studied it.

The porting code was basically smooth, but I found that there was no ConfigurationManager in the .net core, so I couldn't read and write configuration files. I thought it was troublesome to write an XML separately, so I Googled it and found a method. I recorded it as follows, which is convenient for searching in the future:

The method is as follows

Configuration file structure

public class DemoSettings
{
 public string MainDomain { get; set; }
 public string SiteName { get; set; }
}

Show effect

{
 "DemoSettings": {
 "MainDomain": "",
 "SiteName": "My Main Site"
 },
 "Logging": {
 "IncludeScopes": false,
 "LogLevel": {
  "Default": "Debug",
  "System": "Information",
  "Microsoft": "Information"
 }
 }
}

Configure Services

Original configuration

public void ConfigureServices(IServiceCollection services)
{
 // Add framework services.
 ();
}

Customize

public void ConfigureServices(IServiceCollection services)
{
 // Add framework services.
 ();
 
 // Added - uses IOptions<T> for your settings.
 ();
 
 // Added - Confirms that we have a home for our DemoSettings
 <DemoSettings>(("DemoSettings"));
}

Then inject the settings into the corresponding controller and you can use it

public class HomeController : Controller
{
 private DemoSettings ConfigSettings { get; set; }
 
 public HomeController(IOptions<DemoSettings> settings)
 {
  ConfigSettings = ;
 }
 
 public IActionResult Index()
 {
  ViewData["SiteName"] = ;
  return View();
 }
}

Summarize

The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.