Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have to publish multiple versions of the same .NET Core 3.1 based console applications, these versions are identical, the only difference between these versions is an hardcoded server address to which they need to connect.

My question is, how I can change the value of an hardcoded variable at compilation time basing on .NET publish configuration?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
143 views
Welcome To Ask or Share your Answers For Others

1 Answer

I agree with the comments that you should use configuration files or environment variables If you still insist to hard code all your values you could do something like that.

Hard code your variables.

public const string UrlDev = "";
public const string UrlProd = "";

and when you are about to use the url you can do like in your app

var url = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development" ? UrlDev : UrlProd

The Environment variables can be passed to your application on publish like this

dotnet publish /p:Configuration=Release /p:EnvironmentName=Development

The line above will create the following snippet in the csproj file

    <environmentVariables>
      <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" />
    </environmentVariables>

So you publish with Environment vairables already attached on the application and then you make a decision which url to use on this variable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...