确定 Azure webrole 中的 webapp 代码是否为 运行

Determine if webapp code is running in Azure webrole or not

确定我的 Web 应用程序代码在 Azure Web 角色(或模拟器)中是否 运行 的最佳方法是什么?

我需要配置依赖项注入容器并且不想依赖任何 Azure 特定程序集,除非我 运行 在 Azure 中。

this question 的两个答案都需要引用 Azure 特定的程序集,我想在我的内部部署场景中阻止这些程序集。

更新:我真的在运行时环境中寻找可以从我的 Web 应用程序代码中查询的东西。

您可以通过 web.config / app.config / ServiceConfiguration.cscfg 设置来执行此操作,该设置仅在您想要的特定环境中设置。

添加一个参数,例如:

<Setting name="PaaS" value="true" />

然后,在应用程序启动时,获取值:

public bool IsPaaS
{
    get
    {
        var res = false;
        var val = CloudConfigurationManager.GetSetting("PaaS") ?? "false";
        Boolean.TryParse(val, out res);
        return res;
    }
}
如果没有 cscfg 设置,

CloudConfigurationManager.GetSetting 将回退,并检查 web.config and/or app.config.

WebRole 中设置此项,但在本地 IIS 下 运行 时不在 web.config 中设置,以获得您正在寻找的行为。

您可以通过门户(或 ARM 模板)为您的 Web 应用程序设置应用程序设置,然后在您的代码中检查其值。

App settings through the Azure Portal

var isPaaSSetting = Environment.GetEnvironmentVariable("IS_PAAS");
var isPaaS = !string.IsNullOrEmpty(isPaaSSetting) && isPaaSSetting.ToUpper() == "TRUE";
if (isPaaS) {...}