deen
deen

Reputation: 487

ASP.NET Core - How to read EnvironmentVariableTarget after hosting in IIS

I have set MyConnString in System's environment variable in Windows 10 manually. I am trying to read it from code. In Visual Studio I can get the value of MyConnString using EnvironmentVariableTarget.User.

But after publishing and hosted in IIS, the value of MyConnString is returned as empty/null. My log is not printing the 'MyConnString' value.

My connection string is sensitive and can't be part of any config file. I appreciate your help.

I am using ASP.NET Core 3.1 and my app pool identity is ApplicationPoolIdentity. I have also set Load User Profile true in app pool.

var content = Environment.GetEnvironmentVariable("MyConnString", EnvironmentVariableTarget.User);

if (string.IsNullOrWhiteSpace(content))
{
    content = Environment.GetEnvironmentVariable("MyConnString", EnvironmentVariableTarget.Machine);
}

if (string.IsNullOrWhiteSpace(content))
{
    content = Environment.GetEnvironmentVariable("MyConnString", EnvironmentVariableTarget.Process);
}

if (string.IsNullOrWhiteSpace(content))
{
    content = Environment.GetEnvironmentVariable("MyConnString");
}

Upvotes: 0

Views: 1303

Answers (1)

Nicola Biada
Nicola Biada

Reputation: 2800

The User of IIS is not your user.

FIRST OPTION

You need to set the variable for the user owner of the process of your IIS.

SECOND OPTION

Use Environment variables inside your web.<environment>.config in order to be compatible in every server you deploy.

web.Staging.config

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <location>
        <system.webServer>
            <aspNetCore>
                <environmentVariables xdt:Transform="InsertIfMissing">
                    <environmentVariable name="MyConnString"
                                         value="my db conn string"
                                         xdt:Locator="Match(name)"
                                         xdt:Transform="InsertIfMissing" />
                </environmentVariables>
            </aspNetCore>
        </system.webServer>
    </location>
</configuration>

you have other possibilities to set the environment variables for your target server, search on G for more infos.

Upvotes: 1

Related Questions