从 NuGet 包中排除目标框架

Exclude target framework from NuGet package

如何从 nuspec(NuGet 包)生成中排除特定的目标框架?

这是我的 csproj:

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFrameworks>netstandard2.0;net5.0;net5.0-windows</TargetFrameworks>
        <IsPackable>true</IsPackable>
    </PropertyGroup>

    <PropertyGroup Condition="'$(TargetFramework)' == 'net5.0-windows'">
        <IsPackable>false</IsPackable>
    </PropertyGroup>
</Project>

dotnet pack 命令生成包含所有目标框架的 NuGet 包,不仅 netstandard2.0net5.0

生成的 nuspec:

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
  <metadata>
    <id>ExampleLibrary</id>
    <version>1.0.0</version>
    <authors>ExampleLibrary</authors>
    <description>Package Description</description>
    <dependencies>
      <group targetFramework="net5.0" />
      <group targetFramework="net5.0-windows7.0" />
      <group targetFramework=".NETStandard2.0" />
    </dependencies>
  </metadata>
</package>
<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFrameworks>netstandard2.0;net5.0;net5.0-windows7.0</TargetFrameworks>
        <IsPackable>true</IsPackable>
        <GenerateNuspecDependsOn>$(GenerateNuspecDependsOn);_ExcludeTargetFramework;_ExcludeTargetFrameworkDependency</GenerateNuspecDependsOn>
    </PropertyGroup>

    <Target Name="_ExcludeTargetFramework" AfterTargets="_GetTargetFrameworksOutput" BeforeTargets="_WalkEachTargetPerFramework">
        <ItemGroup>
            <_TargetFrameworks Remove="net5.0-windows7.0" />
        </ItemGroup>
    </Target>

    <Target Name="_ExcludeTargetFrameworkDependency" AfterTargets="_WalkEachTargetPerFramework" BeforeTargets="GenerateNuspec">
        <ItemGroup>
            <_FrameworksWithSuppressedDependencies Include="net5.0-windows7.0" />
        </ItemGroup>
    </Target>
</Project>

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
  <metadata>
    <id>ExampleLibrary</id>
    <version>1.0.0</version>
    <authors>ExampleLibrary</authors>
    <description>Package Description</description>
    <dependencies>
      <group targetFramework="net5.0" />
      <group targetFramework=".NETStandard2.0" />
    </dependencies>
  </metadata>
</package>