Search code examples
c#visual-studioasp.net-coremsbuildcsproj

MsBuild DefineConstants from .pubxml doesnt work correctly


I have ASP.NET Core + Blazor app (default template) with 2 projects.

When I create an IIS publish profile:

<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
  <PropertyGroup>
    <WebPublishMethod>MSDeploy</WebPublishMethod>
    <LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <ExcludeApp_Data>false</ExcludeApp_Data>
    <ProjectGuid>04df5cd2-b320-4d8c-85bd-d25cd9b83925</ProjectGuid>
    <SelfContained>false</SelfContained>
    <MSDeployServiceURL>https://mytestserver.com:8172/msdeploy.axd</MSDeployServiceURL>
    <DeployIisAppPath>TestApp</DeployIisAppPath>
    <RemoteSitePhysicalPath />
    <SkipExtraFilesOnServer>true</SkipExtraFilesOnServer>
    <MSDeployPublishMethod>WMSVC</MSDeployPublishMethod>
    <EnableMSDeployBackup>true</EnableMSDeployBackup>
    <EnableMsDeployAppOffline>true</EnableMsDeployAppOffline>
    <_TargetId>IISWebDeploy</_TargetId>

    <DefineConstants>ModuleOneTest</DefineConstants>
  </PropertyGroup>
</Project>

So <DefineConstants>ModuleOneTest</DefineConstants> affects only code in Server project (which contain publish profile) and code:

public string GetConstants()
{
    List<string> constants = new List<string>();
#if ModuleOneTest
    constants.Add("ModuleOneTest From Server");
#endif

    return string.Join(", ", constants);
}

This works and add test string ("ModuleOneTest From Server") but in referenced project (client project added to server as a reference by default template) this is not working:

public string GetConstants()
{
    List<string> constants = new List<string>();
#if ModuleOneTest
    constants.Add("ModuleOneTest From Client");
#else
    constants.Add("Not defined");
#endif

    return string.Join(", ", constants);
}

and it returns "Not defined".

How can I fix this issue to work correctly with multiple projects?


Solution

  • To add conditional symbol, modify the client project file as shown below:

    <PropertyGroup Condition="'$(ModuleOneTestEnabled)'=='true'">
      <DefineConstants>$(DefineConstants);ModuleOneTest</DefineConstants>
    </PropertyGroup>
    

    Pass the property on server side publish profile for that you can use this command:

    dotnet publish Serverapp.csproj /p:ModuleOneTestEnabled=true /p:PublishProfile=ProfileName