Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access dotnet's environment variable via build target

Tags:

.net

msbuild

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>
like image 761
Shahar Shokrani Avatar asked Oct 20 '25 04:10

Shahar Shokrani


1 Answers

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'
like image 95
Paweł Łukasik Avatar answered Oct 21 '25 20:10

Paweł Łukasik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!