MSBuild:如何针对多RID选择性发布多个项目
解决方案配置调整方案
1. 调整Directory.Build.props全局配置
修正全局RID配置,并通过条件设置实现Windows专属项目的RID过滤:
<Project> <!-- 原有默认配置保留 --> <PropertyGroup> <IsPublishable>false</IsPublishable> <BasePublishDir>$(SolutionDir)PublishOutput</BasePublishDir> <!-- 全局声明要发布的RID集合 --> <RuntimeIdentifiers>win-x64;linux-x64</RuntimeIdentifiers> <!-- 统一PublishDir模板,自动拼接RID与项目子目录 --> <PublishDir>$(BasePublishDir)\$(RuntimeIdentifier)\$(PublishSubDir)</PublishDir> </PropertyGroup> <!-- 针对net8.0-windows项目,仅保留win-x64 RID --> <PropertyGroup Condition="'$(TargetFramework)' == 'net8.0-windows'"> <RuntimeIdentifiers>win-x64</RuntimeIdentifiers> </PropertyGroup> </Project>
注意:需将原有项目csproj中设置的
<PublishDir>改为<PublishSubDir>,例如原<PublishDir>$(BasePublishDir)\ApiService</PublishDir>替换为<PublishSubDir>ApiService</PublishSubDir>,让全局模板自动生成带RID的输出路径。
2. 修改Directory.Build.targets实现多RID批量发布
调整自定义目标OurTarget,遍历每个RID执行发布,同时确保Windows专属项目只处理对应RID:
<Project> <PropertyGroup> <CISuppressLocalPublish>true</CISuppressLocalPublish> </PropertyGroup> <!-- 多RID发布主目标 --> <Target Name="OurTarget"> <!-- 遍历全局RID集合,逐个执行Rebuild+Publish --> <MSBuild Projects="$(MSBuildProjectFile)" Targets="Rebuild;Publish" Properties="RuntimeIdentifier=%(RuntimeIdentifiers.Identity)" Condition="Exists('%(RuntimeIdentifiers.Identity)')" /> </Target> <!-- Windows专属项目遇到linux-x64时跳过发布 --> <Target Name="SkipLinuxPublishForWindowsProjects" BeforeTargets="Publish" Condition="'$(TargetFramework)' == 'net8.0-windows' and '$(RuntimeIdentifier)' == 'linux-x64'"> <Message Text="Skipping linux-x64 publish for Windows-only project: $(MSBuildProjectName)" Importance="High" /> <PropertyGroup> <PublishTargetDisabled>true</PublishTargetDisabled> </PropertyGroup> </Target> <!-- 标记跳过的项目直接禁用Publish目标 --> <Target Name="DisablePublishIfSkipped" BeforeTargets="Publish" Condition="'$(PublishTargetDisabled)' == 'true'"> <PropertyGroup> <PublishDependsOn></PublishDependsOn> </PropertyGroup> </Target> </Project>
3. 项目csproj适配修改
对需要发布的项目,替换原有硬编码的<PublishDir>为<PublishSubDir>:
<!-- 通用项目示例 --> <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <IsPublishable>true</IsPublishable> <PublishSubDir>WebApi</PublishSubDir> </PropertyGroup> </Project> <!-- Windows专属项目示例 --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net8.0-windows</TargetFramework> <IsPublishable>true</IsPublishable> <PublishSubDir>WindowsService</PublishSubDir> </PropertyGroup> </Project>
4. 命令行调用验证
保持原有命令行即可,无需额外指定RID:
msbuild /t:OurTarget OurSolution.slnx <other-args>
关键说明
- 目录分离核心:通过
<MSBuild>任务遍历每个RID单独执行发布,确保每个RID的输出路径正确拼接。 - Windows项目过滤:props阶段优先覆盖RID集合,target阶段再做二次条件跳过,双重保障避免误发布。
- 评估顺序适配:props在项目加载阶段评估,确保Windows项目仅加载win-x64;target在执行阶段处理具体发布逻辑,补全最后一道过滤。
内容的提问来源于stack exchange,提问作者T2PS
相关产品推荐
相关产品推荐

