專案上線時,圖片、CSS、JS 等靜態資源常需部署至 CDN 或獨立靜態伺服器,域名也可能變更。將域名集中配置在 Web.config 或靜態類別中,可避免頁面散落硬編碼 URL,降低維護成本。
建立 WebConfig.cs:
public static class WebConfig
{
public static readonly string ResourceServer = "https://static.example.com/";
public static readonly string ApiBaseUrl = "https://api.example.com/";
}
前台頁面引用:
<script src="<%= WebConfig.ResourceServer %>js/jquery.min.js"></script>
<link rel="stylesheet" href="<%= WebConfig.ResourceServer %>css/style.css" />
<img src="<%= WebConfig.ResourceServer %>images/logo.png" alt="Logo" />
Web.config:
<appSettings>
<add key="ResourceServer" value="https://static.example.com/" />
<add key="ApiBaseUrl" value="https://api.example.com/" />
</appSettings>
封裝 Helper:
public static class ConfigHelper
{
public static string ResourceServer => ConfigurationManager.AppSettings["ResourceServer"];
public static string ApiBaseUrl => ConfigurationManager.AppSettings["ApiBaseUrl"];
}
頁面使用同上,僅將 WebConfig.ResourceServer 改為 ConfigHelper.ResourceServer。
利用 Web.Debug.config / Web.Release.config 轉換:
<!-- Web.Release.config -->
<appSettings xdt:Transform="Replace">
<add key="ResourceServer" value="https://cdn.prod.com/" />
</appSettings>
發布時自動切換,無需修改代碼。
此模式同樣適用於 API 端點、信箱伺服器、第三方服務 URL 等所有需環境區分的配置項。