iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 20
1
自我挑戰組

後端或是ASP.NET Core的學習筆記系列 第 20

第20天:使用ASP.NET Core DI取得appsettings.json 組態設定檔字串

假設你的一些設定值是可以調整的,那你可以把值放在appsettings.json檔裡面。當程式取得appsettings.json的值後再決定做什麼事情之類的。

例如我圖片中在appsettings.json裡面放了帳號密碼

https://ithelp.ithome.com.tw/upload/images/20201005/20120420ioqMFalreL.png

那我在程式中要取得帳號密碼的話,在要用的類別建構函式加入參數IConfiguration configuration,並建立一個IConfiguration _config藍未來儲存起來

...省略...
using Microsoft.Extensions.Configuration;

namespace WebApplication8.Controllers
{
    public class ProductController : Controller
    {
        ...省略...
        private readonly IConfiguration _config;
        public ProductController(IConfiguration configuration, ...省略...)
        {
            ...
            _config = configuration;
        }
        ...省略...
    }
}

https://ithelp.ithome.com.tw/upload/images/20201005/20120420duoeLaB4WL.png

在你要取得設定值的地方,使用GetValue,並指定要取得的值是什麼<格式>,就可以取得appsettings.json裡面指定資料的值

var account = _config.GetValue<string>("MyData:DBAccount");
var password = _config.GetValue<string>("MyData:DBPassword");


上一篇
第19天:Tag Helpers標籤協助程式
下一篇
第21天:將EF Core的資料庫連線字串改由appsettings.json提供
系列文
後端或是ASP.NET Core的學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言