【问题标题】:How to access local appsettings in Azure Function如何在 Azure Function 中访问本地应用设置
【发布时间】:2018-08-21 07:28:03
【问题描述】:

我真的很难找到如何从 Azure 函数中创建的实例访问应用程序设置。

我有以下代码...

namespace ThingServiceFunctionApp
{    
    public static class RoleFunctions
    {
        [FunctionName("GetThings")]
        public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "roles")]HttpRequest req, ILogger log)
        {
            return await FunctionApp.GetFunction<IGetThingsFunction>().RunAsync(req, log).ConfigureAwait(false);
        }


    public static class FunctionApp
    {
        private static readonly IFunctionFactory FuncFactory = new FunctionFactory(new Startup());

        public static IFunction GetFunction<TFunction>() where TFunction : IFunction
        {
            return FuncFactory.Create<TFunction>();
        }
    }


     public class Startup : IStartup
     {

          private IConfiguration Configuration { get; }

          public Startup()
          {
              Configuration = new ConfigurationBuilder()
                  .SetBasePath(Directory.GetCurrentDirectory())
                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                  .AddEnvironmentVariables()
                  .Build();
          }


          public IServiceCollection ConfigureServices(IServiceCollection services)
          {
              services
                  .AddSingleton<IThingService, ThingService>()
                  .AddTransient<IGetThingsFunction, GetThings>();

              return services;
          } 
        }
      }
  }

如何从 ThingService 或 GetThings 函数中访问 Configuration 中的值?

不相关,但仅供参考,我已经添加了我自己对 DI 的支持(代码未显示) - 因此是 .AddSingleton 等。

谢谢!

【问题讨论】:

  • 只需使用您的Configuration(将其传递到正确的位置)?有什么问题?
  • 嗨,这是一个很好的观点 - 但是据我所知,在网络应用程序中,配置是注入的(所以像构造函数中的 IConfig 一样),这将是更可取的。我可能是错的......

标签: c# azure configuration azure-functions


【解决方案1】:

在我们的项目中,我们将本地配置文件中的变量添加到 Azure 门户中的应用程序设置。

像这样创建对象: new ConfigurationBuilder().AddEnvironmentVariables().Build();

然后像往常一样检索它们,即 Configuration["Key"];

【讨论】:

  • 好的,谢谢 - 我如何在本地进行测试?在我以前的 Web 应用程序中,我有本地应用程序设置文件,该文件被 Azure 门户中的应用程序设置覆盖。
  • 不确定这是否是最好的方法,但我们所做的基本上是 "if (File.Exists(localSettingsFile)) //create local config; else //create azure config"
  • 谢谢 - 我猜它是否有效..!我会做一些调查
【解决方案2】:

要在 Azure Function 中访问本地应用设置(无论是在 Azure 上还是本地调试。),我们可以这样做:

public static string GetEnvironmentVariable(string name)
{
    return name + ": " +
        System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
}

更多信息供您参考:Environment variables

【讨论】:

  • 所以这要么从门户获取,如果存在,或者从 appsettings.json 获取?抱歉,直到今天晚上我才能测试任何东西,否则我就试一试吧!我会在 5 分钟后阅读链接...谢谢!
猜你喜欢
  • 2021-05-22
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多