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.


Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay