0

I have a web application in .NET 8 hosted in an Azure web app.

I have added a connection string in environment variables and want to access it in the program.cs file when we normally pass the connection string to the DbContext class:

 var services = new ServiceCollection();
 builder.Services.AddDbContext<EmployeeDbContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

Azure Web App

I checked the same with copilot, it gave me this code, but it errors at:

builder.Configuration.AddAzureAppConfiguration();
builder.Configuration.Build();

-------------------

using Microsoft.Extensions.Configuration;
    
var builder = WebApplication.CreateBuilder(args);
    
// Add Azure App Configuration
builder.Configuration.AddAzureAppConfiguration(Environment.GetEnvironmentVariable("DefaultConnection"));
    
// Build the configuration
var config = builder.Configuration.Build();
    
// Access the connection string
string connectionString = config.GetConnectionString("YourConnectionStringName");

Edit

I have also tried this code, but I'm not able to get the connection string:

string connString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddDbContext<EmployeeDbContext>(options =>
    options.UseSqlServer(connString));

Null connection string

Due to this I am getting this error:

An unhandled exception occurred while processing the request. InvalidOperationException: The ConnectionString property has not been initialized.
Microsoft.Data.SqlClient.SqlConnection.PermissionDemand()

Unhandled exception

Help appreciated

1 Answer 1

1

Values in Azure environment variables aren't part of "Azure App Configuration" - that's a separate service.

To get at a connection string defined in the Azure Environment Variables, you're already using the correct code:

// get your connection string from the Azure app service's 
// "Environment variables / Connection strings" settings
string connString = builder.Configuration.GetConnectionString("DefaultConnection");

// use connection string for your DbContext class
builder.Services.AddDbContext<EmployeeDbContext>(options =>
    options.UseSqlServer(connString));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.