如何基于发布配置更改硬编码变量? [英] How to change hardcoded variables basing on publish configuration?

查看:52
本文介绍了如何基于发布配置更改硬编码变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须发布同一基于.NET Core 3.1的控制台应用程序的多个版本,这些版本是相同的,这些版本之间的唯一区别是它们需要连接到的硬编码服务器地址.

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.

我的问题是,如何基于.NET发布配置在编译时更改硬编码变量的值?

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

推荐答案

我同意应使用配置文件或环境变量的注释,如果您仍然坚持对所有值进行硬编码,则可以执行类似的操作.

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.

对变量进行硬编码.

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

上面的行将在csproj文件中创建以下代码段

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

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

因此,您将发布已附加在应用程序上的Environment vairables,然后决定要在此变量上使用哪个url.

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

这篇关于如何基于发布配置更改硬编码变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆