[ASP.NET] 設置與取得 Web.config 自定義資料
FakeStandard
Posted on November 25, 2024
在 ASP.NET 應用程式裡,我們可將動態資料儲存於組態檔之中,也就是 Web.config,為避免將資料寫死於程式裡形成 hardcode,未來程式上線後,可讓維護者僅透過修改組態檔資料,即可改變程式的參數賦值,而無須重新修改程式碼
在 Web.config 找到 appSettings 屬性,以下為預設的設置。
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
由於 appSettings 屬性是 key-value 型別,設置方法很簡單,將自行定義的名稱賦值給 key,這裡可看作為參數的名稱,而該參數欲存放的資料值給 value
<appSettings>
<add key="Greeting" value="Hello World" />
</appSettings>
接著從 Controller 中讀取 appSettings,首先引用 System.Configuration
Namespace,讀取方式也非常簡單
using System.Configuration;
public ActionResult GetAppSettingsProperty()
{
var message = ConfigurationManager.AppSettings["Greeting"].ToString();
return Content(message);
}
打完,收工!
Thanks for reading the article 🌷 🌻 🌼
If you like it, please don't hesitate to click heart button ❤️
or follow my GitHub ⭐ I'd appreciate it.
💖 💪 🙅 🚩
FakeStandard
Posted on November 25, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
dotnetcore .NET 9 Improvements for ASP.NET Core: Open API, Performance, and Tooling
November 16, 2024