首页 > 解决方案 > 根据环境配置 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 通常忽略的一个,这样如果它的源代码开放,它将不会显示。

更聪明的方法是什么?

标签: c#azure

解决方案


如果您希望为本地工作或测试和部署编译不同的代码,您可以使用预定义的 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 的顶部菜单附近设置是否处于调试或发布模式。

调试/发布组合框


推荐阅读