Method of using appsettings. json configuration file in ASP. NET core Web

  • 2021-09-16 06:42:07
  • OfStack

Preface

Recently, I studied the transplantation of asp. net program to linux, and just as net core came out, I studied it.

The transplant code basically goes smoothly, but it is found that there is no ConfigurationManager in net core, and it is impossible to read and write configuration files. It is too troublesome to write an xml alone. It is Google and found a method, which is recorded as follows to facilitate future search:

The method is as follows

Configuration file structure


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

Display effect in appsettings. json

appsettings.json


{
 "DemoSettings": {
 "MainDomain": "http://www.mysite.com",
 "SiteName": "My Main Site"
 },
 "Logging": {
 "IncludeScopes": false,
 "LogLevel": {
  "Default": "Debug",
  "System": "Information",
  "Microsoft": "Information"
 }
 }
}

Configuring Services

Original configuration


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

Customize


public void ConfigureServices(IServiceCollection services)
{
 // Add framework services.
 services.AddMvc();
 
 // Added - uses IOptions<T> for your settings.
 services.AddOptions();
 
 // Added - Confirms that we have a home for our DemoSettings
 services.Configure<DemoSettings>(Configuration.GetSection("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 = settings.Value;
 }
 
 public IActionResult Index()
 {
  ViewData["SiteName"] = ConfigSettings.SiteName;
  return View();
 }
}

Summarize


Related articles: