c# - 根据环境配置 URL
问题描述
我发布了一个网站(MVC 前端)和一个 API,它托管在 Azure 上的两个不同域上。MVC 前端调用 API(通过 url),但现在,我在本地工作和部署它之间手动切换 url:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://myApiDomain.azurewebsites.net"); //https://localhost:44393/
/* I set one URL as
baseaddress and keep
the other in a comment,
depending on environment */
现在它被设置为托管的 API 地址,myApiDomain。所以如果我在本地工作,我会交换这两个地址。当我部署时,我放回了 azurewebsites-url。
此外,我不希望将 URL 直接提交到源代码,而是可能是配置文件或类似文件 - 最好是 git 通常忽略的一个,这样如果它的源代码开放,它将不会显示。
更聪明的方法是什么?
解决方案
如果您希望为本地工作或测试和部署编译不同的代码,您可以使用预定义的 DEBUG 宏。例子:
using System;
namespace debugorrelease
{
class Program
{
static void Main( string[] args )
{
#if DEBUG
Console.WriteLine( "I am in debug mode, which is used for development." );
#else
Console.WriteLine( "I am in release mode, which is used for deployment." );
#endif
}
}
}
您可以在 Visual Studio 的顶部菜单附近设置是否处于调试或发布模式。
推荐阅读
- python - What is the string format "%g%%" mean in python 3?
- c - C:散列金字塔模式
- android - 按包名称阻止特定应用安装
- c# - Newtonsoft JSON.NET 创建一个类型字典
- symfony - Symfony 1.4 - SecurityError: Blocked a frame with origin "[url]" from access a cross-origin frame
- python - 基于 Django 类的视图中“数据”的关键错误
- javascript - 在turnjs区域触发fancybox
- android - 自定义视图:配置更改的奇怪行为
- java - RabbitMQ:查找由于消费者异常而导致通道关闭的原因
- c# - Kofax 导出连接器注册