1、前言
在大多數的應用程序中,一些參數需要寫在配置文件里,以此增加系統(tǒng)的靈活性。在ASP.NET
時代,配置參數一般會寫在web.config
文件中,其本質上是對XML
文件的讀取和寫入。而在ASP.NET Core
中,配置文件變成了appsettings.json
文件。相較于XML
,JSON
文件更加輕量且靈活,下面就來介紹一下如何在ASP.NET Core
中對其進行讀寫操作。
2、添加配置參數
打開appsettings.json
文件,添加如下配置項。如果對JSON
文件的格式不熟悉,建議先了解一下其格式規(guī)范,其代碼如下所示:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ConnectionString": "Data Source=DSF-PC;Initial Catalog=Dao;User ID=sa;Password=123456"
},
"AppName": "ASP.NET Core API", // 應用程序名稱
"Author": "HerryDong", // 作者
"AppSettings": {
"DefaultLanguage": "zh-CN", // 默認語言
"MinLevel": 10, // 地圖最小層級
"MaxLevel": 16, // 地圖最大層級
"Center": {
"Longitude": 120, // 地圖中心點經度
"Latitude": 30 // 地圖中心點維度
}
}
}
3、基于配置節(jié)點名稱的讀取
3.1、注入IConfiguration接口
在ASP.NET Core
中,如果希望通過配置項的名稱獲取配置參數,那就需要用到IConfiguration
接口。該接口已經默認存在于IoC
容器中,無需手動注冊。創(chuàng)建一個新的控制器HomeController
,在構造函數中注入IConfiguration
接口,代碼如下所示:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
namespace App.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class HomeController : ControllerBase
{
private readonly IConfiguration configuration;
/// <summary>
/// 構造函數
/// </summary>
/// <param name="configuration"></param>
public HomeController(IConfiguration configuration)
{
this.configuration = configuration;
}
}
}
3.2、讀取配置參數
在HomeController
中添加一個Get
方法,添加如下代碼:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
namespace App.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class HomeController : ControllerBase
{
private readonly IConfiguration configuration;
/// <summary>
/// 構造函數
/// </summary>
/// <param name="configuration"></param>
public HomeController(IConfiguration configuration)
{
this.configuration = configuration;
}
/// <summary>
/// 讀取配置參數
/// </summary>
/// <returns></returns>
[HttpGet]
public string Get()
{
string connectionString = configuration.GetConnectionString("ConnectionString");
string appName = configuration["AppName"];
string author = configuration["Author"];
string defaultLanguage = configuration["AppSettings:DefaultLanguage"];
string minLevel = configuration["AppSettings:MinLevel"];
string maxLevel = configuration["AppSettings:MaxLevel"];
string longitude = configuration["AppSettings:Center:Longitude"];
string latitude = configuration["AppSettings:Center:Latitude"];
return connectionString + "\n" + appName + "\n" + author + "\n" +
defaultLanguage + "\n" + minLevel + "\n" + maxLevel + "\n" +
longitude + "\n" + latitude;
}
}
}
3.2.1、數據庫連接字符串
對于數據庫連接字符串ConnectionString
,可以直接通過IConfiguration
接口的GetConnectionString
方法進行獲取:
string connectionString = configuration.GetConnectionString("ConnectionString");
3.2.2、一級子節(jié)點
由于AppName
、Author
位于一級節(jié)點,因此可通過如下方式進行獲?。?/p>
string appName = configuration["AppName"];
string author = configuration["Author"];
3.2.3、二級子節(jié)點
二級節(jié)點DefaultLanguage
、MinLevel
、MaxLevel
位于一級節(jié)點AppSettings
下,因此需要通過添加一個冒號:
的方式進行獲取:
string defaultLanguage = configuration["AppSettings:DefaultLanguage"];
string minLevel = configuration["AppSettings:MinLevel"];
string maxLevel = configuration["AppSettings:MaxLevel"];
3.2.4、三級子節(jié)點
三級節(jié)點Longitude
、Latitude
位于二級節(jié)點Center
下,因此需要通過添加兩個冒號::
的方式進行獲取:
string longitude = configuration["AppSettings:Center:Longitude"];
string Latitude = configuration["AppSettings:Center:Latitude"];
通過配置節(jié)點名稱獲取配置參數的方法比較直觀,在寫法上只需要注意配置節(jié)點所在的層級即可,程序運行結果如下圖所示:
4、基于配置文件實體類的讀取
4.1、構建配置文件實體類
ASP.NET Core
也允許通過配置文件實體類的方式讀取配置文件。首先根據appsettings.json
中各個節(jié)點的層級關系構建相應實體類ConfigModel
,其代碼如下所示:
namespace App
{
public class ConfigModel
{
public ConnectionStrings ConnectionStrings { get; set; }
public string AppName { get; set; }
public string Author { get; set; }
public AppSettings AppSettings { get; set; }
}
public class ConnectionStrings
{
public string ConnectionString { get; set; }
}
public class AppSettings
{
public string DefaultLanguage { get; set; }
public int MinLevel { get; set; }
public int MaxLevel { get; set; }
public Center Center { get; set; }
}
public class Center
{
public double Longitude { get; set; }
public double Latitude { get; set; }
}
}
4.2、注冊配置文件實體類
在構建完配置文件實體類后,我們需要在Startup.cs
文件中對其進行注冊,調用services.Configure
方法即可,代碼如下所示:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace App
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// 注冊配置文件實體類
services.Configure<ConfigModel>(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
4.3、注入IOptions接口
這里需要注意,原先通過配置節(jié)點名稱讀取配置參數值的時候,我們注入的是IConfiguration
接口,而這里則需要換成IOptions
接口,最后通過IOptions.Value
獲取實體類。由于IOptions
接口默認存在于IoC
容器中,因此無需手動對其進行注冊。其代碼如下所示:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
namespace App.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class HomeController : ControllerBase
{
private readonly ConfigModel model;
/// <summary>
/// 構造函數
/// </summary>
/// <param name="options"></param>
public HomeController(IOptions<ConfigModel> options)
{
this.model = options.Value;
}
}
}
4.4、讀取配置參數
現在我們已經獲取了配置文件實體類,接下來的工作很簡單了,由于是強類型操作,Visual Studio 2019
會幫助你自動感知配置項,其代碼如下所示:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
namespace App.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class HomeController : ControllerBase
{
private readonly ConfigModel model;
/// <summary>
/// 構造函數
/// </summary>
/// <param name="options"></param>
public HomeController(IOptions<ConfigModel> options)
{
this.model = options.Value;
}
/// <summary>
/// 讀取配置參數
/// </summary>
/// <returns></returns>
[HttpGet]
public string Get()
{
string connectionString = model.ConnectionStrings.ConnectionString;
string appName = model.AppName;
string author = model.Author;
string defaultLanguage = model.AppSettings.DefaultLanguage;
int minLevel = model.AppSettings.MinLevel;
int maxLevel = model.AppSettings.MaxLevel;
double longitude = model.AppSettings.Center.Longitude;
double latitude = model.AppSettings.Center.Latitude;
return connectionString + "\n" + appName + "\n" + author + "\n" +
defaultLanguage + "\n" + minLevel + "\n" + maxLevel + "\n" +
longitude + "\n" + latitude;
}
}
}
與IConfiguration
接口讀取配置參數的方法相比,IOptions
接口的優(yōu)勢是可以利用實體類進行映射和讀取,這也可以杜絕由于寫錯配置項名稱而引起錯誤的弊端。程序運行結果如下圖所示:
5、寫入配置文件
5.1、獲取appsettings.json的路徑
其實在實際開發(fā)過程中,微軟并不推薦開發(fā)者對appsettings.json
文件進行動態(tài)修改,一些需要動態(tài)配置的參數最好寫在其他文件中,但在某些特殊情況下我們還是得這么干。話說回來,既然涉及到文件修改,那我們肯定得先獲取這個文件的路徑,否則一切免談。在ASP.NET Core
中,如果要獲取一個文件的路徑,我們可以使用IWebHostEnvironment
接口,在使用時只需要將其注入控制器的構造函數即可,由于它已經默認存在于IoC
容器中,因此我們無需進行手動注冊,代碼如下所示:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System.IO;
namespace App.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class HomeController : ControllerBase
{
private readonly IWebHostEnvironment webHostEnvironment;
/// <summary>
/// 構造函數
/// </summary>
/// <param name="webHostEnvironment"></param>
public HomeController(IWebHostEnvironment webHostEnvironment)
{
this.webHostEnvironment = webHostEnvironment;
}
/// <summary>
/// 獲取文件路徑
/// </summary>
/// <returns></returns>
[HttpGet]
public string Get()
{
string filePath = Path.Combine(webHostEnvironment.ContentRootPath, "appsettings.json");
return filePath;
}
}
}
運行一下程序,發(fā)現可以正確獲取appsettings.json
文件的路徑,如下圖所示:
5.2、修改配置參數
我們可以借助Newtonsoft.Json
來實現配置參數的修改,使用NuGet
將其引入,如下圖所示:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using System.IO;
namespace App.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class HomeController : ControllerBase
{
private readonly IWebHostEnvironment webHostEnvironment;
/// <summary>
/// 構造函數
/// </summary>
/// <param name="webHostEnvironment"></param>
public HomeController(IWebHostEnvironment webHostEnvironment)
{
this.webHostEnvironment = webHostEnvironment;
}
/// <summary>
/// 修改配置參數
/// </summary>
/// <returns></returns>
[HttpGet]
public string Get()
{
try
{
// 讀取appsettings.json文本內容
string filePath = Path.Combine(webHostEnvironment.ContentRootPath, "appsettings.json");
string text = System.IO.File.ReadAllText(filePath);
// 修改配置項
JObject obj = JObject.Parse(text);
obj["AppName"] = "API";
obj["Author"] = "Herry";
obj["AppSettings"]["DefaultLanguage"] = "en-US";
obj["AppSettings"]["MinLevel"] = 15;
obj["AppSettings"]["MaxLevel"] = 20;
obj["AppSettings"]["Center"]["Longitude"] = 130;
obj["AppSettings"]["Center"]["Latitude"] = 40;
// 重新寫入appsettings.json
string result = obj.ToString();
System.IO.File.WriteAllText(filePath, result);
return "success";
}
catch
{
return "failed";
}
}
}
}
運行程序,發(fā)現appsettings.json
的配置項修改成功。但也可以發(fā)現一個問題:原先的注釋都沒了,因此最好不要對該文件進行動態(tài)修改。程序運行結果如下圖所示:
5.3、注入IOptionsSnapshot接口
現在我們已經實現了appsettings.json
文件的修改,但如果仍舊使用IOptions
接口讀取配置參數會怎么樣呢?看下面一段代碼:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using System.IO;
namespace App.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class HomeController : ControllerBase
{
private readonly IWebHostEnvironment webHostEnvironment;
private readonly ConfigModel model;
/// <summary>
/// 構造函數
/// </summary>
/// <param name="webHostEnvironment"></param>
/// <param name="options"></param>
public HomeController(IWebHostEnvironment webHostEnvironment,
IOptions<ConfigModel> options)
{
this.webHostEnvironment = webHostEnvironment;
this.model = options.Value;
}
/// <summary>
/// 修改配置參數
/// </summary>
/// <returns></returns>
[HttpGet]
public string Get()
{
try
{
// 讀取appsettings.json文本內容
string filePath = Path.Combine(webHostEnvironment.ContentRootPath, "appsettings.json");
string text = System.IO.File.ReadAllText(filePath);
// 修改
JObject obj = JObject.Parse(text);
obj["AppName"] = "API";
obj["Author"] = "Herry";
obj["AppSettings"]["DefaultLanguage"] = "en-US";
obj["AppSettings"]["MinLevel"] = 15;
obj["AppSettings"]["MaxLevel"] = 20;
obj["AppSettings"]["Center"]["Longitude"] = 130;
obj["AppSettings"]["Center"]["Latitude"] = 40;
// 重新寫入appsettings.json
string result = obj.ToString();
System.IO.File.WriteAllText(filePath, result);
return "success";
}
catch
{
return "failed";
}
}
/// <summary>
/// 讀取配置參數
/// </summary>
/// <returns></returns>
[HttpGet]
public string Get_2()
{
string connectionString = model.ConnectionStrings.ConnectionString;
string appName = model.AppName;
string author = model.Author;
string defaultLanguage = model.AppSettings.DefaultLanguage;
int minLevel = model.AppSettings.MinLevel;
int maxLevel = model.AppSettings.MaxLevel;
double longitude = model.AppSettings.Center.Longitude;
double latitude = model.AppSettings.Center.Latitude;
return connectionString + "\n" + appName + "\n" + author + "\n" +
defaultLanguage + "\n" + minLevel + "\n" + maxLevel + "\n" +
longitude + "\n" + latitude;
}
}
}
在執(zhí)行完Get
方法后,我們再執(zhí)行Get_2
方法,發(fā)現好像不太對,怎么讀出來的還是修改前的配置參數?
其實,如果對appsettings.json
文件做了修改,那么就不能使用IOptions
接口去讀取配置參數了,因為該接口實例被注冊為全局單例生命周期,因此無法讀到最新的配置參數。在這種情況下,我們需要使用另一個接口來實現配置參數的讀取,那就是IOptionsSnapshot
接口,由于該接口被注冊為域生命周期,因此每次http
訪問都能讀取到最新配置,其代碼如下所示:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using System.IO;
namespace App.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class HomeController : ControllerBase
{
private readonly IWebHostEnvironment webHostEnvironment;
private readonly ConfigModel model;
/// <summary>
/// 構造函數
/// </summary>
/// <param name="webHostEnvironment"></param>
/// <param name="options"></param>
public HomeController(IWebHostEnvironment webHostEnvironment,
IOptionsSnapshot<ConfigModel> options)
{
this.webHostEnvironment = webHostEnvironment;
this.model = options.Value;
}
/// <summary>
/// 修改配置參數
/// </summary>
/// <returns></returns>
[HttpGet]
public string Get()
{
try
{
// 讀取appsettings.json文本內容
string filePath = Path.Combine(webHostEnvironment.ContentRootPath, "appsettings.json");
string text = System.IO.File.ReadAllText(filePath);
// 修改
JObject obj = JObject.Parse(text);
obj["AppName"] = "API";
obj["Author"] = "Herry";
obj["AppSettings"]["DefaultLanguage"] = "en-US";
obj["AppSettings"]["MinLevel"] = 15;
obj["AppSettings"]["MaxLevel"] = 20;
obj["AppSettings"]["Center"]["Longitude"] = 130;
obj["AppSettings"]["Center"]["Latitude"] = 40;
// 重新寫入appsettings.json
string result = obj.ToString();
System.IO.File.WriteAllText(filePath, result);
return "success";
}
catch
{
return "failed";
}
}
/// <summary>
/// 讀取配置參數
/// </summary>
/// <returns></returns>
[HttpGet]
public string Get_2()
{
string connectionString = model.ConnectionStrings.ConnectionString;
string appName = model.AppName;
string author = model.Author;
string defaultLanguage = model.AppSettings.DefaultLanguage;
int minLevel = model.AppSettings.MinLevel;
int maxLevel = model.AppSettings.MaxLevel;
double longitude = model.AppSettings.Center.Longitude;
double latitude = model.AppSettings.Center.Latitude;
return connectionString + "\n" + appName + "\n" + author + "\n" +
defaultLanguage + "\n" + minLevel + "\n" + maxLevel + "\n" +
longitude + "\n" + latitude;
}
}
}
運行程序,發(fā)現可以讀取到最新的配置參數,結果如下圖所示:
文章來源:http://www.zghlxwxcb.cn/news/detail-458088.html
6、結語
本文主要介紹了ASP.NET Core
中配置文件的讀寫方法。在實際開發(fā)過程中,如果涉及到項目遷移,即:之前已經存在很多配置參數,我們可以使用IConfiguration
接口讀取配置參數,如果是新的項目,則可以考慮使用IOptions
接口讀取,因為強類型的讀取方法可以避免因配置項名稱寫錯而引發(fā)的一系列問題。文章來源地址http://www.zghlxwxcb.cn/news/detail-458088.html
到了這里,關于ASP.NET Core 3.1系列(4)——讀寫配置文件appsettings.json的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!