萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET Web.config 配置全解析:核心區段、最佳實踐與安全強化

Web.config 架構總覽

Web.config 是 ASP.NET 應用程式的 XML 配置檔,採用分層繼承:Machine.config → 根 Web.config → 應用程式 Web.config → 子目錄 Web.config。核心區段:

核心區段詳細說明

1. `` - 自定義區段聲明

<configSections>
  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false" />
  <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework" requirePermission="false" />
  <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
    <section name="MyApp.Properties.Settings" type="System.Configuration.ClientSettingsSection" requirePermission="false" />
  </sectionGroup>
</configSections>

2. `` / `` - 應用程式設定

<!-- 傳統 appSettings (所有值為字串) -->
<appSettings>
  <add key="ConnectionString" value="Server=.;Database=MyDb;Integrated Security=true;" />
  <add key="MaxUploadSizeMB" value="10" />
  <add key="EnableFeatureX" value="true" />
</appSettings>

<!-- 強型別 applicationSettings (推薦新專案) -->
<applicationSettings>
  <MyApp.Properties.Settings>
    <setting name="MaxUploadSizeMB" serializeAs="String">
      <value>10</value>
    </setting>
  </MyApp.Properties.Settings>
</applicationSettings>

讀取:`ConfigurationManager.AppSettings["Key"]` 或 `Properties.Settings.Default.MaxUploadSizeMB`。

3. `` - 資料庫連接字串

<connectionStrings>
  <add name="DefaultConnection" 
       connectionString="Server=.;Database=MyDb;Integrated Security=true;TrustServerCertificate=true;MultipleActiveResultSets=true" 
       providerName="System.Data.SqlClient" />
  <add name="RedisConnection" 
       connectionString="localhost:6379,password=xxx,ssl=false,abortConnect=false" 
       providerName="StackExchange.Redis" />
</connectionStrings>

生產環境必須加密:`aspnet_regiis -pef "connectionStrings" "物理路徑"`

4. `` - ASP.NET 執行期核心配置

<system.web>
  <!-- 編譯設定 -->
  <compilation targetFramework="4.8" debug="false" batch="true" optimizeCompilations="true">
    <assemblies>
      <add assembly="System.Web.Mvc, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </assemblies>
  </compilation>

  <!-- HTTP 運行時 -->
  <httpRuntime targetFramework="4.8" 
               maxRequestLength="102400"        <!-- 100MB 上傳限制 -->
               executionTimeout="300"           <!-- 5分鐘請求逾時 -->
               requestValidationMode="4.5"      <!-- 請求驗證模式 -->
               enableVersionHeader="false"      <!-- 隱藏版本資訊 -->
               fcnMode="Disabled" />            <!-- 檔案變更通知 -->

  <!-- 頁面預設 -->
  <pages enableViewStateMac="true" 
         viewStateEncryptionMode="Auto" 
         controlRenderingCompatibilityVersion="4.0" 
         clientIDMode="AutoID" 
         validateRequest="true" 
         enableEventValidation="true">
    <namespaces>
      <add namespace="System.Web.Optimization" />
    </namespaces>
    <controls>
      <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </controls>
  </pages>

  <!-- 身份驗證與授權 -->
  <authentication mode="Forms">
    <forms name=".ASPXAUTH" 
           loginUrl="~/Account/Login" 
           timeout="30" 
           slidingExpiration="true" 
           protection="All" 
           requireSSL="true" 
           cookieless="UseDeviceProfile" />
  </authentication>
  
  <authorization>
    <deny users="?" /> <!-- 拒絕匿名 -->
  </authorization>

  <!-- Session 狀態 -->
  <sessionState mode="InProc" 
                cookieless="false" 
                timeout="20" 
                regenerateExpiredSessionId="true" />
  <!-- 生產建議:mode="SQLServer" 或 "Custom" (Redis) -->

  <!-- 全域化 -->
  <globalization requestEncoding="utf-8" 
                 responseEncoding="utf-8" 
                 fileEncoding="utf-8" 
                 culture="zh-TW" 
                 uiCulture="zh-TW" />

  <!-- 自定義錯誤 -->
  <customErrors mode="RemoteOnly" defaultRedirect="~/Error/500.aspx">
    <error statusCode="404" redirect="~/Error/404.aspx" />
    <error statusCode="403" redirect="~/Error/403.aspx" />
  </customErrors>

  <!-- 追蹤 -->
  <trace enabled="false" localOnly="true" pageOutput="false" requestLimit="100" mostRecent="true" />

  <!-- 會員/角色/設定檔 提供者 -->
  <membership defaultProvider="SqlMembershipProvider">...</membership>
  <roleManager enabled="true" defaultProvider="SqlRoleProvider">...</roleManager>
</system.web>

5. `` - IIS 7+ 整合管線配置

<system.webServer>
  <!-- 模組管線 -->
  <modules runAllManagedModulesForAllRequests="false">
    <remove name="FormsAuthentication" />
    <remove name="Session" />
    <add name="CustomAuthModule" type="MyApp.Modules.CustomAuthModule" />
  </modules>

  <!-- 處理常式對應 -->
  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" 
         path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" 
         preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>

  <!-- 靜態內容快取 -->
  <staticContent>
    <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
    <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
    <mimeMap fileExtension=".webp" mimeType="image/webp" />
  </staticContent>

  <!-- 壓縮 -->
  <urlCompression doStaticCompression="true" doDynamicCompression="true" />
  <httpCompression>
    <dynamicTypes>
      <add mimeType="application/json" enabled="true" />
      <add mimeType="application/javascript" enabled="true" />
    </dynamicTypes>
  </httpCompression>

  <!-- 安全標頭 -->
  <httpProtocol>
    <customHeaders>
      <add name="X-Content-Type-Options" value="nosniff" />
      <add name="X-Frame-Options" value="DENY" />
      <add name="X-XSS-Protection" value="1; mode=block" />
      <add name="Referrer-Policy" value="strict-origin-when-cross-origin" />
      <add name="Content-Security-Policy" value="default-src 'self'; script-src 'self' 'unsafe-inline' cdn.example.com;" />
    </customHeaders>
  </httpProtocol>

  <!-- 重寫規則 -->
  <rewrite>
    <rules>
      <rule name="Redirect HTTP to HTTPS" stopProcessing="true">
        <match url="(.*)" />
        <conditions>
          <add input="{HTTPS}" pattern="^OFF$" />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
      </rule>
    </rules>
  </rewrite>

  <!-- 安全性 -->
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="104857600" /> <!-- 100MB -->
      <fileExtensions>
        <add fileExtension=".config" allowed="false" />
        <add fileExtension=".json" allowed="false" />
      </fileExtensions>
      <hiddenSegments>
        <add segment="App_Data" />
        <add segment=".git" />
      </hiddenSegments>
    </requestFiltering>
  </security>
</system.webServer>

6. `` - CLR 執行期設定

<runtime>
  <!-- 組件綁定重定向 -->
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
    </dependentAssembly>
  </assemblyBinding>
  
  <!-- GC 設定 (大型應用) -->
  <gcServer enabled="true" /> <!-- 伺服器 GC:多執行緒、獨立堆 -->
  <gcConcurrent enabled="true" /> <!-- 背景 GC -->
  
  <!-- 非同步流程控制 -->
  <ThreadPoolSettings minWorkerThreads="100" minIoThreads="100" />
</runtime>

安全強化清單

  1. 加密敏感區段:`connectionStrings`、`appSettings` (含密鑰)、`system.web/machineKey`
  2. 移除版本標頭:`enableVersionHeader="false"` + `httpProtocol/customHeaders` 移除 `X-AspNet-Version`、`X-Powered-By`
  3. 請求過濾:封鎖 `.config`、`.json`、`.log`、隱藏 `App_Data`、`bin`、`.git`
  4. HTTPS 強制:`requireSSL="true"`、HSTS、重寫規則 HTTP→HTTPS
  5. Cookie 安全:`httpOnlyCookies="true"`、`requireSSL="true"`、`sameSite="Lax/Strict"`
  6. 錯誤資訊隱藏:`customErrors mode="RemoteOnly"`、`httpErrors errorMode="Custom"`
  7. CSP 標頭:限制腳本/樣式/字體來源,防 XSS

環境差異化配置



  
    
    
  
  
    
  




  
    
  
  
    
    
  

結語

Web.config 是 ASP.NET 應用程式的「大腦中樞」。精通其結構、區段語義、繼承規則、轉換機制,能讓部署更可靠、安全更穩固、效能更可控。現代化趨勢:ASP.NET Core 採用 `appsettings.json` + 環境變數 + Key Vault,但配置管理的核心原則(分層、類型安全、敏感資料保護、環境隔離)始終相通。

copyright © 萬盛學電腦網 all rights reserved