How to check Azure function is running on local environment? `RoleEnvironment` is not working in Azure Functions

无人久伴 提交于 2019-12-09 02:35:09

问题


I have a condition in code where i need to check if current environment is not local.i have used !RoleEnvironment.IsEmulated, now this is not working in Azure functions but works in Cloud service. Same code is Shared in Cloud service also, so solution should work with cloud service and azure functions.

how can i check current environment is local not hosted/deployed?


回答1:


Based on answer by Fabio Cavalcante, here is a working Azure function that checks the current running environment (local or hosted):

using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System;

namespace AzureFunctionTests
{
    public static class WhereAmIRunning
    {
        [FunctionName("whereamirunning")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            bool isLocal = string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID"));

            string response = isLocal ? "Function is running on local environment." : "Function is running on Azure.";

            return req.CreateResponse(HttpStatusCode.OK, response);
        }
    }
}



回答2:


You can use an approach similar to what the actual runtime uses to identify whether it is running on Azure: https://github.com/Azure/azure-webjobs-sdk-script/blob/efb55da/src/WebJobs.Script/Config/ScriptSettingsManager.cs#L25

In this case, the runtime checks for the presence of an app setting named WEBSITE_INSTANCE_ID




回答3:


You can use the AZURE_FUNCTIONS_ENVIRONMENT environment variable, which is set automatically:

Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT"); // set to "Development" locally

https://github.com/Azure/azure-functions-host/issues/4491



来源:https://stackoverflow.com/questions/45026215/how-to-check-azure-function-is-running-on-local-environment-roleenvironment-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!