SYSLIB0003:不支持代码访问安全性

代码访问安全性(CAS) 是不支持的旧技术。 启用 CAS 的基础结构(仅在 .NET Framework 2.x - 4.x 中存在)已弃用,不会接收服务或安全修补程序。

因此,从 .NET 5 开始,.NET 中的大多数代码访问安全性(CAS)相关类型已过时。 这包括 CAS 属性,例如 SecurityPermissionAttributeCAS 权限对象,例如 SocketPermissionEvidenceBase派生类型和其他支持 API。 使用这些 API 会在编译时生成警告 SYSLIB0003

过时的 CAS API 的完整列表如下所示:

解决方法

  • 如果要断言任何安全权限,请删除声明权限的属性或调用。

    // REMOVE the attribute below.
    [SecurityPermission(SecurityAction.Assert, ControlThread = true)]
    public void DoSomething()
    {
    }
    public void DoAssert()
    {
        // REMOVE the line below.
        new SecurityPermission(SecurityPermissionFlag.ControlThread).Assert();
    }
    
  • 如果拒绝或限制(通过 PermitOnly)任何权限,请联系安全顾问。 由于 .NET 5+ 运行时不遵循 CAS 属性,因此如果应用程序错误地依赖 CAS 基础结构来限制对这些方法的访问,则应用程序可能会有安全漏洞。

    // REVIEW the attribute below; could indicate security vulnerability.
    [SecurityPermission(SecurityAction.Deny, ControlThread = true)]
    public void DoSomething()
    {
    }
    public void DoPermitOnly()
    {
        // REVIEW the line below; could indicate security vulnerability.
        new SecurityPermission(SecurityPermissionFlag.ControlThread).PermitOnly();
    }
    
  • 如果要求任何权限(除外 PrincipalPermission),请删除需求。 所有需求将在运行时成功。

    // REMOVE the attribute below; it will always succeed.
    [SecurityPermission(SecurityAction.Demand, ControlThread = true)]
    public void DoSomething()
    {
    }
    public void DoDemand()
    {
        // REMOVE the line below; it will always succeed.
        new SecurityPermission(SecurityPermissionFlag.ControlThread).Demand();
    }
    
  • 如果您要求 PrincipalPermission,请参阅关于 SYSLIB0002 的指南:PrincipalPermissionAttribute 已过时。 该指南均适用于 PrincipalPermissionPrincipalPermissionAttribute

禁止显示警告

如果必须使用过时的 API,可以在代码或项目文件中禁止显示警告。

若要仅取消单个冲突,请将预处理器指令添加到源文件以禁用,然后重新启用警告。

// Disable the warning.
#pragma warning disable SYSLIB0003

// Code that uses obsolete API.
// ...

// Re-enable the warning.
#pragma warning restore SYSLIB0003

若要取消项目中的所有 SYSLIB0003 警告,请将属性 <NoWarn> 添加到项目文件。

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
   ...
   <NoWarn>$(NoWarn);SYSLIB0003</NoWarn>
  </PropertyGroup>
</Project>

有关详细信息,请参阅 禁止显示警告

另请参阅