我最终得出的答案适用于 Visual Studio 2010 和 Visual Studio 2012;把它放在你的 web 应用程序的 .csproj 文件的末尾之前:
<Project...
[...]
<!-- The following makes sure we can't accidentally publish a non-Release configuration from within Visual Studio -->
<Target Name="PreventNonReleasePublish2010" BeforeTargets="PipelinePreDeployCopyAllFilesToOneFolder" Condition="'$(BuildingInsideVisualStudio)'=='true' AND '$(VisualStudioVersion)'=='10.0'">
<Error Condition="'$(Configuration)'!='Release'" Text="When publishing from Visual Studio 2010, you must publish the Release configuration!" />
</Target>
<Target Name="PreventNonReleasePublish2012" BeforeTargets="MSDeployPublish" Condition="'$(BuildingInsideVisualStudio)'=='true' AND '$(VisualStudioVersion)'=='11.0'">
<Error Condition="'$(Configuration)'!='Release'" Text="When publishing from Visual Studio 2012, you must publish the Release configuration!" />
</Target>
</Project>
继续阅读以了解我在此答案背后的想法,但基本上它围绕这样一个事实,即 Visual Studio 2010 定义了要连接的 PipelinePreDeployCopyAllFilesToOneFolder 目标,而 Visual Studio 2012 定义了更“标准”的 MSDeployPublish 目标上钩。
上述代码仅允许在 Visual Studio 中的 Release 配置中部署发布,但可以轻松修改它以阻止 所有从 Visual Studio 中部署发布。
AFAIR,Visual Studio 2010 上下文菜单中的“发布”调用 webdeploy\msdeploy 工具。我玩了一点,但我一点也不喜欢。如果您仍想使用此功能并将目标插入某处 - 您需要知道确切的目标及其依赖属性。
检查
c:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets
您会发现两个任务 - MSDeploy 和 VSMSDeploy。后一个听起来很适合我。这个文件中根本没有使用第一个。但是 VSMSDeploy 在三个不同的目标中使用,
PackageUsingManifest、TestDeployPackageToLocal 和 MSDeployPublish。后一个听起来不错;)
<Target Name="MSDeployPublish" DependsOnTargets="$(MSDeployPublishDependsOn)">
所以你只需要覆盖一个属性。将它放在您的目标之前,“YourTargetName”将在 MSDeployPublish 之前被调用。
<PropertyGroup>
<MSDeployPublishDependsOn Condition="'$(MSDeployPublishDependsOn)'!=''">
$(MSDeployPublishDependsOn);
YourTargetName;
</MSDeployPublishDependsOn>
</PropertyGroup>
如果您已经切换到 MSBuild 4.0,则有一种更简单的方法来挂钩您的目标。您只需要指定BeforeTarget 属性。在我们的例子中,它将是这样的:
<Target Name="MyTarget" BeforeTargets="MSDeployPublish">
<Error Condition="'foo'=='foo'" Text="test publish error" />
</Target>
我希望这会有所帮助。询问您是否还有其他问题。
PS:我没有检查所有这些,因为我没有任何支持 MSDeploy 的环境;)
注意:我记得我不鼓励将 MSDeploy 用于我们自己的产品,因为为continuous integration (CI) 系统正确配置它是非常违反直觉的。也许我不是很擅长,你的解决方案会正常工作。但请谨慎使用 MSDeploy。