ASP.NET 從 Web.Config / App.Config 讀取 Property 的方式


  1. 說明
    1. 設定 Config
    2. 加入參考
    3. 使用 Config
  2. 相關連結

筆記 ASP.NET 如何在 Web.Config 讀取 Property。

logo

說明

ASP.NET Web 應用程式可以於 Web.config 讀取資料;Console 應用程式 可以於 App.config 讀取資料。

設定 Config

在 Web.config / App.config appSettings 區段中加入要從程式讀取的 Property (Key-value)

<appSettings>
  <add key="myProperty" value="Hello World" />
  ...
</appSettings>

加入參考

ASP.NET MVC 專案預設已經加入 System.Configuration 參考,但 Console 應用程式專案需自行加入參考。

使用 Config

從 Controller 中進行讀取,需要使用 System.Configuration Namespace

using System.Configuration;

public ActionResult ReadProperty()
{
  var property = ConfigurationManager.AppSettings["MyProperty"];
  return Content(property);
}

相關連結

ASP.NET MVC 從無到有打造一個應用系統

Visual Studio 入門教學