Home > Article > Backend Development > Detailed example of using appsettings.json configuration file in core Web (ASP.NET)
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!