Home > Enterprise >  Can't access dotnet's environment variable via build target
Can't access dotnet's environment variable via build target

Time:06-30

I'm trying to access the ASPNETCORE_ENVIRONMENT environment variable inside a Target's Build event.

The .csproj looks like this:

<Project Sdk="Microsoft.NET.Sdk.Web">

    <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
    </PropertyGroup>

    <Target Name="MyPostBuild" BeforeTargets="Build">
        <Exec Command="echo Operating System: $(OS)"/>
        <Exec Command="echo ASPNETCORE_ENVIRONMENT: $(ASPNETCORE_ENVIRONMENT)"/>
    </Target>

</Project>

The launchSettings.json contain the environment variable:

"profiles": {
    "DemoProject": {
        "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        }
    }
} 

It outputs the $(OS) very well but it does not prints the ASPNETCORE_ENVIRONMENT:

Operating System Windows_NT

ASPNETCORE_ENVIRONMENT:

My question is how to access the ASPNETCORE_ENVIRONMENT value within a Build event in order to make the build event run only with a specific condition like this:

<Target Name="MyPostBuild" BeforeTargets="Build" Condition="'$(ASPNETCORE_ENVIRONMENT)' == 'Development'">
    Do something
</Target>

CodePudding user response:

launchSettings.json is used when you run your application. The values from there are not available in compile time. That's why you get an empty string when trying to read the value.

What you could do instead is to do a condition based on one of the values that are available like Configuration.

'$(Configuration)' == 'Debug'
  • Related