Home  >  Article  >  Backend Development  >  Detailed example of using appsettings.json configuration file in core Web (ASP.NET)

Detailed example of using appsettings.json configuration file in core Web (ASP.NET)

Y2J
Y2JOriginal
2017-04-27 10:11:223960browse

This article mainly introduces how to use the appsettings.json configuration file in ASP.NET core Web. The article gives detailed sample code. Friends in need can refer to it. Let’s take a look.

Preface

Recently I have been studying the porting of asp.net programs to Linux. It just so happened that .net core came out, so I started studying.

The transplantation of the code was basically smooth, but I found that there is no ConfigurationManager in .net core, and the configuration file cannot be read and written. It was troublesome to write a separate xml, so I googled it and found a method, so I recorded it 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"
 }
 }
}

Configuration Services

Original configuration

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

Customization

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 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();
 }
}

Summary

The above is the detailed content of Detailed example of using appsettings.json configuration file in core Web (ASP.NET). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn