我有 ASP.NET Core 5 项目
<Project Sdk="Microsoft.NET.Sdk.Web">
包含 appsettings.json。构建操作未自定义:内容,如果较新则复制。
如何在另一个 csproj 中引用此项目,以便 appsettings.json 不会包含在输出文件夹中?
<ProjectReference Include="..\..\src\app\App.csproj">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>compile</IncludeAssets>
<ExcludeAssets>contentfiles; build; analyzers; buildtransitive</ExcludeAssets>
</ProjectReference>
正常情况下,
AllowedReferenceRelatedFileExtensions
属性可以处理引用项目的runtine、输出文件,例如第二个项目的pdb、xml、dev.json...,而不是较新的资源文件的副本。并且第一个项目上没有这样的直接 msbuild 属性来防止引用的资源文件被复制到其中。
作为测试,您可以在主项目而不是引用项目上尝试
AllowedReferenceRelatedFileExtensions
属性:
<AllowedReferenceRelatedFileExtensions>*.pdb</AllowedReferenceRelatedFileExtensions>
你会发现App项目的pdb文件丢失了。确实如此。
当您使用 App 项目中的
a new copy if newer txt resource file
对其进行测试时,它永远不会起作用。
<AllowedReferenceRelatedFileExtensions>*.txt</AllowedReferenceRelatedFileExtensions>
解决方案
到目前为止,最好的功能是删除主
_CopyOutOfDateSourceItemsToOutputDirectory
系统目标之后的文件,该系统目标负责将引用项目中的所有资源、输出文件复制到主项目中:
<Target Name="DeleteFile" AfterTargets="_CopyOutOfDateSourceItemsToOutputDirectory">
<Delete Files="$(TargetDir)xxx.appsettings.json"></Delete>
</Target>
在一系列 Visual Studio 更新后,这个问题再次引起了我的注意。
虽然我无法阻止引用的项目文件被复制到输出文件夹,但我可以在引用项目配置文件中使用以下代码:
<PropertyGroup>
...
<RunPostBuildEvent>Always</RunPostBuildEvent>
</PropertyGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="del /f "$(IntermediateOutputPath)$(TargetFileName)"" />
</Target>
这会在构建后删除缓存的输出文件,以确保它始终被构建。因此,它的文件总是最后写入,覆盖引用项目中的任何内容。