.NET Framework 4 引入 Level 2 透明度模型(與 Silverlight 相同),大幅改變 AllowPartiallyTrustedCallers (APTCA) 組件的安全性語意。本文詳細說明遷移所需的屬性標記與工具輔助。
[assembly: AllowPartiallyTrustedCallers] 移除 LinkDemand,允許部分信任呼叫者存取。SecurityTransparent 程式碼無法直接呼叫 SecurityCritical 程式碼。| 屬性 | 權限 | 可被透明程式碼呼叫 | 適用場景 |
|---|---|---|---|
SecurityTransparent | 低(不可執行危險操作) | 是 | 大多數非敏感邏輯(預設) |
SecurityCritical | 高(可執行任何特權操作) | 否 | 內部核心邏輯、危險 API 封裝 |
SecuritySafeCritical | 高(同 Critical) | 是 | 受控公開給部分信任的安全進入點(橋樑) |

SecuritySafeCritical(謹慎使用,需嚴格驗證輸入/輸出、權限要求)。SecurityCritical。.NET Framework SDK 提供 SecAnnotate.exe,掃描組件二進位,建議需標記的透明度屬性。運作機制為多輪掃描:
SecAnnotate.exe /p:1 /d:"referenced assemblies path" MyAssembly.dll
/p:1:僅執行第一輪掃描,避免過度標記 Critical 導致 API 無法被部分信任呼叫。/d:指定參考組件路徑(預設僅搜尋 GAC)。pass 屬性標示輪次,以最新輪次建議為準。v2 版本 使用 LinkDemand 保護 LogLocation setter,Assert 提權刪除日誌。
v4 版本 對應標記:
Usage():無危險操作 → Transparent(無需標記)LogLocation.set:設定敏感路徑 → [SecurityCritical](取代 LinkDemand)SetLogLocation():存取 Critical 成員,但邏輯安全且預期公開 → [SecuritySafeCritical]DeleteLog():Assert 權限刪除檔案,受 LogLocation 保護 → [SecuritySafeCritical]OtherLogging.Usage():覆寫 Transparent 方法且呼叫 Critical 成員 → 必須為 SafeCritical(SecAnnotate 可偵測此規則衝突)Demand),保留部分信任呼叫能力。若短期無法完全遷移,可強制使用 Level 1 規則:
[assembly: SecurityRules(SecurityRuleSet.Level1)]
但不建議長期使用,Level 2 更安全、易審計、且跨平台一致(Silverlight/CoreCLR)。
v4 實作 IFormattable,導致舊代碼 String.Format("{0:r}", timespan) 拋出 FormatException。解決方案:修正格式字串,或在 app.config 啟用舊模式:
<configuration>
<runtime>
<TimeSpan_LegacyFormatMode enabled="true"/>
</runtime>
</configuration>