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

后端 未结 3 1725
庸人自扰
庸人自扰 2021-01-04 00:19

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

3条回答
  •  醉梦人生
    2021-01-04 01:13

    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 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);
            }
        }
    }
    

提交回复
热议问题