ASP.NET Core 是如何讀取配置文件,今天我們來學習。
ASP.NET Core的配置系統已經和之前版本的ASP.NET有所不同了,之前是依賴於System.Configuration和XML配置文件web.config。
新的配置系統支持多種格式的配置文件。
下面我們來以json 格式的配置文件正式開始學習。
我們新建一個ASP.NET Core Web 應用程序,選擇無身份驗證。
讀取配置文件
在項目目錄下有個 appsettings.json ,我們先來操作這個文件。
在appsettings.json 添加如下兩個節點。
{ "Data": "LineZero", "ConnectionStrings": { "DefaultConnection": "數據庫1", "DevConnection": "數據庫2" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } } }
下面我們來讀取。由於項目默認已經將該文件加入ConfigurationBuilder 之中,所以我們可以直接來讀取。
在 Configure 方法中讀取:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { var data = Configuration["Data"]; //兩種方式讀取 var defaultcon = Configuration.GetConnectionString("DefaultConnection"); var devcon = Configuration["ConnectionStrings:DevConnection"];
調試程序,可以看到數據成功取出。
多環境區分
我們復制一個appsettings.json 然后重命名為 appsettings.Development.json
更改appsettings.Development.json 如下:
{ "Data": "LineZero Development", "ConnectionStrings": { "DefaultConnection": "開發數據庫1", "DevConnection": "開發數據庫2" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } } }
然后我們調試程序,你會發現獲取到的值變成了Development.json 里的值。
這里就是多環境配置。
public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)//增加環境配置文件,新建項目默認有 .AddEnvironmentVariables(); Configuration = builder.Build(); }
如果我們直接執行讀取到的就是appsettings.json 的值,因為直接執行時是 Production 環境。
下面是輸出圖:
調試時:
dotnet run 時:
對象讀取
我們在appsettings.json 及 Development.json 都添加一個 SiteConfig 節點。
"SiteConfig": { "Name": "LineZero's Blog", "Info": "ASP.NET Core 開發及跨平台,配置文件讀取" },
然后新建一個SiteConfig 類。
public class SiteConfig { public string Name { get; set; } public string Info { get; set; } }
首先在 ConfigureServices 中添加Options 及對應配置。
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); //添加options services.AddOptions(); services.Configure<SiteConfig>(Configuration.GetSection("SiteConfig")); }
然后我們在 Controller 中讀取。
public class HomeController : Controller { public SiteConfig Config; public HomeController(IOptions<SiteConfig> option) { Config = option.Value; } public IActionResult Index() { return View(Config); } }
對應View Index.cshtml
@model SiteConfig @{ ViewData["Title"] = Model.Name; } <h1>@Model.Name</h1> <h2>@Model.Info</h2>
執行程序 http://localhost:5000/
如果你覺得本文對你有幫助,請點擊“推薦”,謝謝。