Ihostbuilder does not contain a definition for configurewebhostdefaults compile error

Viewed 2157

I have created a .NetCore 3.1 FunctionApp. I am trying to implement the code in the startup.cs to access the Azure KeyVault. I need some guidance as I haven't done before. I have so far able to get the following code from the documentation but not sure how to use it. I am also getting compile time error saying that ihostbuilder does not contain a definition for configurewebhostdefaults at line

 .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

I am not sure why i am getting this error and how to I invoke this method

startup.cs

[assembly: FunctionsStartup(typeof(Startup))]
namespace SRL.CustomerOrder
{
    internal class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            builder.Services.AddScoped<ISrlContext, CustomerManagerContext>();
            builder.Services.AddAutoMapper(typeof(Startup));

           
            builder.Services.AddDbContext<CustomerManagerContext>(options =>
               options.UseSqlServer(Environment.GetEnvironmentVariable(EnviornmentVariables.SrlContext)));

            builder.Services.AddTransient<ICustomerDetailsRepository, CustomerDetailsRepository>();
            builder.Services.AddTransient<ICustomerOrdersRepository, CustomerOrdersRepository>();
            builder.Services.AddTransient<IOrderDetailsRepository, OrderDetailsRepository>();

            
            //?? throw new InvalidOperationException()).EnableSensitiveDataLogging());
        }

       

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((context, config) =>
                {
                    if (context.HostingEnvironment.IsProduction())
                    {
                        var builtConfig = config.Build();

                        AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
                        var keyVaultClient = new KeyVaultClient(
                            new KeyVaultClient.AuthenticationCallback(
                                azureServiceTokenProvider.KeyVaultTokenCallback));

                        config.AddAzureKeyVault(
                            $"https://{builtConfig["KeyVaultName"]}.vault.azure.net/",
                            keyVaultClient,
                            new DefaultKeyVaultSecretManager());
                    }
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

Proposed solution

Read the connection string from local.settings.json using the enviornment variable. Deploy the application. Azure takes care of retrieving the appropriate secret of that enviornment

public override void Configure(IFunctionsHostBuilder builder)
        {
            var connectionString = Environment.GetEnvironmentVariable("ConnectionString");

            builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            builder.Services.AddScoped<ISrlContext, CustomerManagerContext>();
            builder.Services.AddAutoMapper(typeof(Startup));

            builder.Services.AddDbContext<CustomerManagerContext>(options =>
               options.UseSqlServer(connectionString));

            builder.Services.AddTransient<ICustomerDetailsRepository, CustomerDetailsRepository>();
            builder.Services.AddTransient<ICustomerOrdersRepository, CustomerOrdersRepository>();
            builder.Services.AddTransient<IOrderDetailsRepository, OrderDetailsRepository>();
        }
1 Answers

According to my test, if you want to read the secret form Azure key vault in Azure function, please refer to the following code

  1. Save the key vault name as a variable in Azure function app settings

  2. Enable Azure MSI for Azure function

  3. Configure access policy for the MSI

  4. Code

 public static class Http
    {
        private static IConfiguration Configuration;

        static Http()
        {
            AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
            var keyVaultClient = new KeyVaultClient(
                new KeyVaultClient.AuthenticationCallback(
                    azureServiceTokenProvider.KeyVaultTokenCallback));
            Configuration = new ConfigurationBuilder()
                   .AddAzureKeyVault(string.Format("https://{0}.vault.azure.net/", Environment.GetEnvironmentVariable("keyVaultName")), 
                                   keyVaultClient,
                                   new DefaultKeyVaultSecretManager())
                   .Build();

        }

        [FunctionName("Http")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {

           
            log.LogInformation("C# HTTP trigger function processed a request.");
            var f1= Configuration["DBConnectionString"];
            return new OkObjectResult("the DBConnectionString :" + f1);
        }


        
    }

enter image description here

Related