跳到主要內容

Net core AP層的變數設定

載入變數的順序

Net 8 AP層的變數設定

載入變數的順序

當Asp.net core 服務開啟時,會有載入的順序,越晚載入的變數,會蓋掉之前設定的變數

appsettings.{Enviroment}.json -> Environment variables -> Command-line argument ->other sources

使用appsettings.{Enviroment}.json,設定應用程式變數

 {
  "AppConfig": {
    "SmptIP": "gmail.com.tw",
    "SmptPort": "512"
  }
}

使用環境變數,設定應用程式變數

 set AppConfig__SmptIP=smpt.google.com
 set AppConfig__SmptPort=433

使用Command-line argument,設定應用程式變數

 F:\source\WebApplication1\WebApplication1\bin\>WebApplication1.exe --AppConfig:SmptIP="smpt.hotmail.com" --AppConfig:SmptPort=500
 

自我設定appsettings.json檔案路徑

Program.cs 加上AddJsonFile方式來讓保護環境參數檔案

builder.Configuration.AddJsonFile(@"E:\site.appsettings.json");

取得appsettings.{Enviroment}.json的方式

  • (1) 設定建構子IConfiguration參數
 public WeatherForecastController(IConfiguration configuration)
 {
    _configuration = configuration;
 }
  • (2) 設定IConfiguration參數

新增類別:AppSettingOptions

    public class AppSettingOptions
    {
        public const string Appsettings = "AppConfig";
        public required string Site { get; set; } = "www.example.com";
        public required int Port { get; set; } = 500;
    }

appsettings.json

 {
  "ConnectionStrings": {},
  "AppConfig": {
    "Site": "www.google.com.tw",
    "Port": 90
 }

WeatherForecastController.cs: 新增TestGet()方法

  [HttpGet("TestGet", Name = "TestGet")]
 
  public string TestGet() 
  {
      AppSettingOptions? appSettingOptions = _configuration.Get();

      return $"Site:{appSettingOptions?.Site}, Port:{appSettingOptions?.Port}"; 
  }

WeatherForecastController.cs: 新增TestGetValue()方法

 [HttpGet("TestGetValue", Name = "TestGetValue")]
 
 public string TestGetValue()
 {
     string? Site = _configuration.GetValue("AppConfig:Site");
     string? Port = _configuration.GetValue("AppConfig:Port");
 
     return $"Site:{Site}, Port:{Port}";
 }
  • (3) 設定環境變數的方式

WeatherForecastController.cs: 新增TestGetEnv()方法

public string TestGetEnv()
{
    //第一種抓取環境變數的方法
    string? Port2  = System.Environment.GetEnvironmentVariable("SmptPort2");

    //第二種抓取環境變數的方法
    string? Site = _configuration["SmptIP"];
    string? Port = _configuration["SmptPort"]; 

    return $"Site:{Site}, Port:{Port}, Port2:{Port2}";
}

結果:Site:gmail333.com.tw, Port:, Port2:test

取得appsettings.json 檢查變數去卡控

  • AppSettingOptions :加上檢查機制
    public class AppSettingOptions
    {
        public const string Appsettings = "AppConfig";

        public required string Site { get; set; } = "www.example.com";

        [RegularExpression("^\\d{4}$")]
        public required int Port { get; set; } ;
    }
  • appsettings.json : 將port改成字串,後面希望啟動時可以檢查出錯誤
{
  "AppConfig": {
    "Site": "www.google.com.tw",
    "Port": "test"
  }
}
  • Programs.cs
//註冊AppSettingOptions時,可以檢查屬性有沒有符合RegularExpression

builder.Services.AddOptions()
    .Bind(builder.Configuration.GetSection(AppSettingOptions.Appsettings))
    .ValidateDataAnnotations()
    .ValidateOnStart();

出現錯誤,訊息告訴你'AppConfig:Port' to type 'System.Int32,應該是整數

  • WeatherForecastController.cs
 
  private readonly ILogger _logger;
  private readonly IConfiguration _configuration;
  private readonly IOptions _options;
  public WeatherForecastController(ILogger logger,
      IConfiguration configuration,
      IOptions options)
  {
      _logger = logger;
      _configuration = configuration;
      this._options = options;
  }

 [HttpGet("TestGet", Name = "TestGet")]
 public string TestGet() 
 {
     return $"Site:{_options?.Value.Site}, Port:{_options?.Value.Port}"; 
 }

可以看到將Port 改成8080就成功

留言

這個網誌中的熱門文章

JavaBean 和POJO

前言 今天介紹JavaBean和POJO的不同,這兩個名詞在JAVA文章常常被拿來使用以及討論。在JDK1.1時候釋出才有的一個標準架構,很多時候常常被搞混,所以我們特別開闢一章來加以討論。POJO規範在企業級應用已經廣大的被使用的規範。 解釋 POJO : 全名為Plain-old-Java-object,只需要繼承Object就可以,沒有特定規定,只要建立的類別有setter/getter方法都可以稱為POJO JavaBean: JavaBean通常用來封裝多個物件成為單獨物件使用,規範比較嚴格,規則如下 規則 說明 1 需要實作序列(Serializable/Externalizable) 2 不能有參數的建構子( no-arg constructor) 3 需要有公用setter/getter 4 屬性必須要私人(private) 5 屬於特定POJO規則 比較 所有的JavaBean都為POJO,但是所有的POJO不一定為JavaBean 都可以當作重複元件 都必須序列化 特性都為可用性、易用性和持久化使用 - 應用 由圖我們可以知道POJO在應用程式中,主要用來存取資料庫資料達到持久化的目的,並提供給商業邏輯流程處理使用。這種POJO的架構提供程式人員開發時的可以很有規則將資料封裝並加以使用。 範例1. JavaBean(以員工為實例) JavaBean建立員工物件,可以發現Employee物件建構子沒有任何參數,屬性為私有化並setter/getter的命名方式。 //實作序列化 public class Employee implements java.io.Serializable{ private int id; private String name; //無參數建構子 public Employee(){} //以下實作setter/getter public void setId(int id){this.id=id;} public int getId(){return id;} public void setName(String ...

GSON基礎教學

GSON 前言 JSON是很常見的資料交換格式,在JAVA領域常用處理JSON的函式庫:GSON、FastXML和JSON-B,本章節會以GSON為主,學習目標如下 JSON格式說明 GSON 套件函式 GSON: 物件轉換JSON字串 GSON: JSON字串轉換物件 JSON 格式說明 JSON全名為JavaScript Object Notation,它是一種輕量級的資料交換格式,會大為流行的理由,主要是他比傳統用xml更輕巧且容易處理, JSON表達方式物件會用大括弧{},陣列則是用中括號[]。 用JSON字串來表達Employee的物件內容,由JSON字串可以知道物件name、age、sex和salary屬性。 JSON表示員工資料方式: {“name”:”Jack Bryant”, “age”:18, “sex”:”M”,”salary”:3500.00} JSON陣列表示方式: 跟我們使用JAVA的陣列方式類似,內容值可以是數字’、文字、布林、陣列、物件、null等等。 範例: 字串: [“紅”、”橙”、”黃”、”綠”、”青”、”藍”、”紫”} 布林: [true, true, false, false, true, true] GSON 套件函式 Gson為google所發布的函式庫,主要將物件與json字串之間的轉換時方便使用。當我們將JAVA物件轉換成JSON字串稱為 序列化 ,JSON字串轉換至JAVA物件稱為 反序列化 。 GSON: 物件轉換JSON字串 有了JSON基本概念後,我們進入本章重點,首先我們需要建立員工類別(Employee),定義如下 物件 屬性 員工類別 Employee name 名字 age 年紀 sex 性別 salary 薪水 /** * name:員工類別 */ public class Employee implements Serializable { //constructor public Employee(String name, double salary){ this.name = name; this.sala...

H2資料庫(1)-基本安裝與介紹

H2資料庫介紹 H2為嵌入式資料庫,使用java開發,跨平台且內含資料庫管理介面,好處開發階段方便開發人員使用。 比較 詳細比較表: http://www.h2database.com/html/features.html#comparison 由圖比較可以知道,H2比其他資料庫更為優勢,以下會介紹開發時常用的模式: 嵌入式模式Embedded Mode 嵌入式資料庫會與應用程式共用同一JVM底層,在這個模式下persistent或是in-memory資料庫都支援,也沒有連線數的限制。但壞處是只可以給該應用程式使用,其他人無法直接存取資料庫。 伺服器模式 Server Mode 外部應用程式可以藉由JDBC或是OBC的方式連結該資料庫,它也支援persistent或是in-memory資料庫,也沒有連線數的限制。 混合模式 Mixed Mode 同時有嵌入式與伺服器的模式去讓外部應用程式連線或是自己應用程式連線。 安裝H2 database 官方網站: http://www.h2database.com/html/main.html 下載安裝程式 出現安裝連結,本次範例使用 Windows installer 的安裝連結 下載安裝程式後,點擊兩下,進入安裝畫面,按”下一步” 一直按”下一步”後,會出現”完成” 安裝完成後,會出現一個說明網頁,你可以點選Quickstart 它會告訴你,如何進入DBRMS畫面以及開啟資料庫服務 開啟windows的視窗圖示,執行 H2 Console後,會執行H2資料庫 進入DBRMS的登入畫面,使用者預設為”SA”,密碼為空值”“,按下”connect”進入,SQL命令中心 登入後,可以在空白處執行SQL語法 8.大致上安裝H2資料庫滿快速,操作畫面也是很好上手,如果系統在開發階段個人覺的滿推薦給大家使用看看。 參考 H2官方網站