DEV Community

FakeStandard
FakeStandard

Posted on

[ASP.NET] 設置與取得 Web.config 自定義資料

在 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>
Enter fullscreen mode Exit fullscreen mode

由於 appSettings 屬性是 key-value 型別,設置方法很簡單,將自行定義的名稱賦值給 key,這裡可看作為參數的名稱,而該參數欲存放的資料值給 value

<appSettings>
    <add key="Greeting" value="Hello World" />
</appSettings>
Enter fullscreen mode Exit fullscreen mode

接著從 Controller 中讀取 appSettings,首先引用 System.Configuration Namespace,讀取方式也非常簡單

using System.Configuration;

public ActionResult GetAppSettingsProperty()
{
     var message = ConfigurationManager.AppSettings["Greeting"].ToString();

     return Content(message);
}
Enter fullscreen mode Exit fullscreen mode

打完,收工!


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.


Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay