Dot-Net

為什麼我的 .net 應用程序需要完全信任?

  • July 3, 2014

我開發了一個 .net 3.0 應用程序,它是使用 clickonce 部署的。

我想從完全信任轉變為部分信任以簡化部署。

我在visual studio下我的項目的“安全”選項卡中嘗試了“計算權限”工具,答案很清楚:

---------------------------
Microsoft Visual Studio
---------------------------
This application requires full trust to run correctly.

但是,我無法弄清楚為什麼需要完全信任。我嘗試將安全設置更改為“部分信任”,但應用程序在啟動時立即引發 SecurityException :

System.Security.SecurityException   {"Request failed.", Action= "System.Security.Permissions.SecurityAction.LinkDemand"
  at MyNameSpace.Program.Main(String[] args)
  at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
  at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
  at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
  at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
  at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
  at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
  at System.Activator.CreateInstance(ActivationContext activationContext)
  at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
  at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
  at System.Threading.ExecutionContext.runTryCode(Object userData)
  at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
  at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  at System.Threading.ThreadHelper.ThreadStart()

我的軟體可能不需要完全信任(我只使用 https 連接到網路伺服器,並且僅在使用者請求時訪問文件系統,用於導入/導出目的)

我怎樣才能弄清楚為什麼我的應用程序需要完全信任?

看來我的問題是由於我的程序集是強簽名的。

引用自msdn

在強名稱程序集中,LinkDemand 應用於其中的所有可公開訪問的方法、屬性和事件,以將它們的使用限制為完全受信任的呼叫者。要禁用此功能,您必須應用 AllowPartiallyTrustedCallersAttribute 屬性。

我正在向我的程序集添加所需的屬性,我會讓你知道結果如何:

[assembly:AllowPartiallyTrustedCallers]

更新:我已將屬性添加到我的程序集中,但我也在使用一些 .net 程序集。

並非所有.net 程序集都可以被部分信任的程序集使用(這裡有一個列表),即 WCF 程序集(即 System.ServiceModel)不在列表中

但是,Microsoft 聲明可以在部分信任環境中使用 WCF(請參閱此處

我試圖從我的引用中刪除所有不需要的程序集,我在所有程序集中都使用了 AllowPartiallyTrustedCallers,但我仍然被卡住了……

Microsoft 有一個名為permcalc的工具,它分析程序集並生成詳細的 xml 輸出文件,如下所示:

<Type Name="MyClass">
<Method Sig="instance void .ctor()">
<Demand>
<PermissionSet version="1" class="System.Security.PermissionSet">
 <IPermission version="1" class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Unrestricted="true" /> 
 <IPermission version="1" class="System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Unrestricted="true" /> 
...

引用自:https://stackoverflow.com/questions/557713