MSBuild publish dotnet core application

I too had a nightmare with inconsistencies between builds from Visual Studio IDE and the dotnet publish command, that were only fixed by doing it using msbuild.exe instead. Also, using /p:PublishProfiles=theXMLthatVSgenerates.xml never worked, so I had to break out every option into the msbuild command line.

Here's what worked for me:

"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\msbuild.exe" C:\Users\xxxx\Source\Repos\netcore-agent1\CoreAgent1\CoreAgent1.csproj /t:Restore;Rebuild;Publish /p:PublishSingleFile=True /p:SelfContained=True /p:PublishProtocol=FileSystem /p:Configuration=Release /p:Platform=x64 /p:TargetFrameworks=netcoreapp3.1 /p:PublishDir=bin\Release\netcoreapp3.1\publish\win-x64 /p:RuntimeIdentifier=win-x64 /p:PublishReadyToRun=False /p:PublishTrimmed=False

Oh man, I searched for 2-3 days now. And - as always on StackOverflow - shortly after asking I found a working answer myself.

tl;dr:

Project.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netcoreapp2.1</TargetFrameworks>
    <TargetLatestRuntimePatch>true</TargetLatestRuntimePatch>  
    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
    <RootNamespace>Company.Toolset.Exporter</RootNamespace>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
    <RuntimeIdentifiers>win-x86;win-x64</RuntimeIdentifiers>
  </PropertyGroup>
  
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v15.0\WebApplications\Microsoft.WebApplication.targets" />
...

MSBuild command:

msbuild Project\Project.csproj -t:restore /t:Build;Publish /p:Configuration=Release /p:Platform=x86 /p:PublishProfile=x86Profile /p:OutputPath=bin/Publish/x86 (and the same for x64)

Explanation:

I think it was the dotnet build/publish command that wanted me to change TargetFrameworks to TargetFramework. But for MSBuild this is wrong. And dotnet wasn't working here, as the solution is mixing dotnet core and dotnet framework. So that had to be fixed.

The <RuntimeIdentifiers>win-x86;win-x64</RuntimeIdentifiers> was needed by the command. I added it to the *.csproj because I know that I build for windows only (at the moment) and that I need both versions.

I don't really know why I needed this line <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v15.0\WebApplications\Microsoft.WebApplication.targets" /> but without this publishing and using the PublishProfiles didn't work as expected.

Links that helped me to get here: (not sorted)

https://github.com/Microsoft/msbuild/issues/1901

https://github.com/aspnet/vsweb-publish/issues/22

How to Publish Web with msbuild?

ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json

Configure MSBuild output path