0

I cannot get my application settings or connections from Azure Web App update my .net 6.0 minimal api. I've tried using environment variables but that only tells me there's a string value. I've also tried using other methods such as the normal way of reading a config which doesn't work for Azure.

In my Appsettings.json:

{
    "ConnectionStrings": {     
        "Context": "",     
        "Redis": ""   
    },   
    "Logging": {     
        "LogLevel": {       
            "Default": "Information",       
            "Microsoft": "Warning",       
            "Microsoft.Hosting.Lifetime": "Information"     
            }  
    },   
    "Where": "Still AppSettings..." 
}

In my appsettings.development.json:

{
   "ConnectionStrings": {
     "Context": "...",
     "Redis": "..."
   },
   "Logging": {
      "LogLevel": {
         "Default": "Information",
         "Microsoft": "Warning",
         "Microsoft.Hosting.Lifetime": "Information"
      }
   },
   "Where": "Local",
}

On one of my api endpoints I have the following code:

public static string Index(IConfiguration configuration) => configuration["Where"] ?? "Failed";

When I debug this, I get "Local". If I deploy this to Azure I get "Still AppSettings..."...

I've also tried various things in my program.cs

using DocumentFormat.OpenXml.InkML;
using Microsoft.OpenApi.Models;
using Twilio.Services;
using Twilio.Web.Endpoints;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddLogging();
builder.Services.AddApplicationInsightsTelemetry(options => { options.ConnectionString = builder.Configuration.GetSection("ApplicationInsights").GetValue<string>("InstrumentationKey"); });
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "TEST API v1",
        Description = "TEST API documentation",
        Contact = new OpenApiContact() { Name = "CCS Dev", Email = "testing..." }
    });
});
var config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddEnvironmentVariables()
    .Build();
var appSettingValue = config["Where"];
var connection = config.GetConnectionString("Context");
builder.Services.AddScoped(c => new TestContext(builder.Configuration["Context"]));
builder.Services.AddStackExchangeRedisCache(options => { options.Configuration = builder.Configuration.GetConnectionString("Redis"); });
var appSettings = builder.Configuration.GetSection("AppSettings");

builder.Services.AddScoped(c => new TestService(
    c.GetRequiredService<TestContext>(),
    c.GetRequiredService<ILogger<TestService>>()
));
builder.Services.AddAuthorization();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{}

app.UseRouting();

app.UseAuthorization();
app.RegisterHomeAPI();

app.UseSwagger();
app.UseSwaggerUI();

app.Run();

In my Home.cs:

namespace Endpoints
{
    public static class HomeApi
    {
        public static void RegisterHomeAPI(this WebApplication app)
        {
            app.MapGet("/", Index);
            app.MapGet("/Home", Index);
            app.MapGet("/Home/Inxed", Index);
            app.MapPost("/", Index);
            app.MapPost("/Home", Index);
            app.MapPost("/Home/Inxed", Index);
        }
        // GET: Home
        public static string Index(IConfiguration configuration) => configuration["Where"] ?? "Failed";
    }
}

In Azure:
enter image description here

I've checked several blogs that allowed me the opportunity to discover ways that this doesn't work for my instance...
https://build5nines.com/azure-web-app-connection-strings/
https://medium.com/awesome-azure/azure-reading-application-settings-in-azure-functions-asp-net-core-1dea56cf67cf
https://www.c-sharpcorner.com/article/how-to-read-the-app-settings-from-azure-in-net-core/
I've also looked at Microsoft and various stackoverflow questions but nothing seems to work for me.
https://learn.microsoft.com/en-us/azure/app-service/configure-common?tabs=portal
https://learn.microsoft.com/en-us/azure/azure-app-configuration/quickstart-aspnet-core-app?tabs=core6x

  • _" I've tried using environment variables but that only tells me there's a string value"_ - note that corresponding environment variables should look like `ConnectionStrings__Context` and `ConnectionStrings__Redis`. – Guru Stron Apr 07 '23 at 09:29

1 Answers1

1

Iam able to read the App settings from Azure.

I have created a .Net Core 6 Application with Minimal API.

enter image description here

We need to add the configuration file for multiple environments.First get the environment and add it to the ConfigurationBuilder.

Change the ConfigurationBuilder as below

var config = $"appsettings.{app.Environment}.json";
IConfigurationBuilder configBuilder = new ConfigurationBuilder().AddJsonFile("appsettings.json", true)
    .AddJsonFile(config, true)
    .AddEnvironmentVariables();

My Program.cs file after integrating your swagger.

using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddLogging();
builder.Services.AddApplicationInsightsTelemetry(options => { options.ConnectionString = builder.Configuration.GetSection("ApplicationInsights").GetValue<string>("InstrumentationKey"); });
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "TEST API v1",
        Description = "TEST API documentation",
        Contact = new OpenApiContact() { Name = "CCS Dev", Email = "testing..." }
    });
});

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

var config = $"appsettings.{app.Environment}.json";
IConfigurationBuilder configBuilder = new ConfigurationBuilder().AddJsonFile("appsettings.json", true)
    .AddJsonFile(config, true)
    .AddEnvironmentVariables();

var appSettings = builder.Configuration.GetSection("AppSettings");


if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateTime.Now.AddDays(index),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast");


app.MapGet("/appsettings", () =>
{
    var appsett = app.Configuration.GetValue<string>("Where");
    return $"Settings from  {appsett}!";
})
    .WithName("AppSettings");
app.Run();


internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

Local Output when there is value in appsettings.Development.json:

enter image description here

Local Output when there is no value in appsettings.Development.json:

enter image description here

Deployed App Output:

enter image description here

Harshitha
  • 3,784
  • 2
  • 4
  • 9