Solving error NETSDK1152 when upgrading to .NET 6

The cause of the error

When using the .NET 6 SDK to run dotnet publish, you may get the error NETSDK1152. The full error looks something like this:

C:\Program Files\dotnet\sdk\6.0.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.ConflictResolution.targets(112,5): error NETSDK1152: Found multiple publish output files with the same relative path: C:\path\to\project-A\appsettings.json, C:\path\to\project-B\appsettings.json, C:\path\to\project-C\appsettings.json. [C:\path\to\project-A\ProjectA.csproj]

##[error]Error: The process 'C:\Program Files\dotnet\dotnet.exe' failed with exit code 1

This is a breaking change in the .NET 6 SDK which happens when there are multiple files with the same name which should be published to the same location. The case I hit was an ASP.NET Core app referencing a .NET Core app, each of which had an appsettings.json file, both of which were set to be copied to the output directory.

Solution

Do not copy appsettings.json to the output/publish directories if it's not needed (i.e. for the .NET Core project which is being referenced by the ASP.NET Core project). You can control that from your .csproj file:

<ItemGroup>
    <Content Include="appsettings.json">
        <CopyToOutputDirectory>Never</CopyToOutputDirectory>
        <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
        <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </Content>
</ItemGroup>

Alternative solution and why I don't recommend it

There is also a workaround which suppresses this error checking. I don't recommend it though, because it means your build does not have reliable behaviour. Either version of the file could overwrite the other, and you have no control over it. The above solution is better because you get to decide which files need copying and which don't.

If you do want to use the workaround, you can do so by adding the following code to your .csproj file:

<PropertyGroup>
    <ErrorOnDuplicatePublishOutputFiles>false</ErrorOnDuplicatePublishOutputFiles>
</PropertyGroup>