天蓝色的webjob:读取appSettings.json并将配置注入到TimerTrigger

时间:2019-01-12 01:02:35

标签: .net-core azure-webjobs appsettings azure-webjobssdk .net-core-2.2

我无法从webjob的appSettings.json文件中读取配置值。 Webjob使用以下nuget程序包:

enter image description here

我的控制台应用程序(webjob)中有两个设置文件: appsettings.development.json appsettings.production.json

在Main方法中,webjob的配置如下:

 static void Main(string[] args)
    {
        var builder = new HostBuilder()
                .ConfigureWebJobs(webJobConfiguration =>
                {
                    webJobConfiguration.AddTimers();
                    webJobConfiguration.AddAzureStorageCoreServices();  
                })
                .ConfigureAppConfiguration((hostingContext, config) =>
                 {
                     var env = hostingContext.HostingEnvironment;
                     Console.WriteLine("hostingContext.HostingEnvironment: " + env.EnvironmentName);
                     config.SetBasePath(Directory.GetCurrentDirectory())
                     .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true)
                     .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true)
                     .AddEnvironmentVariables().Build();
                 })
                .ConfigureServices((context, serviceCollection) =>
                {
                    serviceCollection.AddSingleton<IConfiguration>(context.Configuration);
                    serviceCollection.AddTransient<SayHelloWebJob>(job => new SayHelloWebJob(context.Configuration));
                })
                .Build();

        builder.Run();
    }

SayHelloWebJob的代码如下:

public class SayHelloWebJob
{
     static IConfiguration _configuration;
    public SayHelloWebJob(IConfiguration config)
    {
        _configuration = config;
        Console.WriteLine("Initialized SayHelloWebJob");
    }

    [Singleton]
    public static void TimerTick([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer)
    {
        Console.WriteLine($"From SayHelloWebJob: Hello at {DateTime.UtcNow.ToString()}");
        var test = _configuration.GetSection("WebJobConfiguration:message").Value;
        Console.WriteLine("Configuration access: message: " + test);
        Console.WriteLine("Configuration access: " + _configuration.GetSection("WebJobConfiguration:api").Value);
        Console.WriteLine("configuration object: "+ _configuration.GetConnectionString("AzureWebJobsStorage"));

    }
}

运行Webjob时,我看到console.writeline日志从不输出要在TimerTick方法中读取的配置。

问题:

  1. 如何将appSettings配置注入TimerTick方法内部?
  2. 我有两个appSettings文件-用于开发和生产。如何确保在生产过程中加载了正确的文件?

下面的示例appSettings.development.json文件:

{
"connectionStrings": {
    "AzureWebJobsStorage": stringhere",
    "AzureWebJobsDashboard": "stringhere"
},
"WebJobConfiguration": {
    "message": "I'm running locally!",
    "pfuWebApiUrl": "API link here",
    "api": "api here",
    "ApplicationInsights": {
        "InstrumentationKey": "key here"
    }
}

}

2 个答案:

答案 0 :(得分:1)

我的喜好是将所有环境配置都签入,并且绝对有可能在运行时根据环境加载正确的文件。

首先在Visual Studio的“属性”窗格中将配置文件设置为“复制到较新的输出目录”,或将其添加到csproj:

    <None Update="base.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </None>
    <None Update="prod.settings.json">
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </None>

现在,您只需要在运行时加载正确的配置即可。

        private static IConfigurationRoot GetConfiguration(string basePath)
        {
            string filename = Constants.IsAzureEnvironment ? "prod.settings.json" : "dev.settings.json";

            IConfigurationBuilder configBuilder = new ConfigurationBuilder()
                .SetBasePath(basePath)
                .AddJsonFile("base.settings.json")
                .AddJsonFile(filename);

            return configBuilder.Build();
        }

我从azure函数的executionContext参数中获取了basePath

        [FunctionName("Function1")]
        public static async Task<IActionResult> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, Microsoft.Azure.WebJobs.ExecutionContext context)
        {
            // context.FunctionAppDirectory
            return new OkResult();
        }

答案 1 :(得分:0)

我用Json.NET来读取json文件。

这是我的json内容:

{

“对象”:{

"name": "cwr"

},

“其他”:“ 123”

}

这是function.cs代码:

 public static void Run([TimerTrigger("0 */1 * * * *")] TimerInfo timer,
        ILogger logger)
    {

        JObject jsonData = JObject.Parse(File.ReadAllText(path));

        logger.LogInformation(jsonData["object"]["name"].ToString());
        logger.LogInformation(jsonData["others"].ToString());

    }

这是输出:

enter image description here

希望这对您有帮助,如果您还有其他问题,请告诉我。