Home > Net >  .NET Core pass configuration section from IIS
.NET Core pass configuration section from IIS

Time:01-20

In appsettingsjson file i have:

  "DataSource": {
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "Root",
    "CollectionName": "ApiLog"
  },

in Program.cs, i get this data like this

builder.Services.Configure<DatabaseSettings>(
    builder.Configuration.GetSection("DataSource"));

where DatabaseSettings class is;

    public class DatabaseSettings
    {
        public string ConnectionString { get; set; } = null!;

        public string DatabaseName { get; set; } = null!;

        public string CollectionName { get; set; } = null!;
    }

Then i can access instance of DatabaseSettings via dependency injection like:

    public class LogService
    {
        private readonly IMongoCollection<Log> _collection;

        public LogService(
            IOptions<DatabaseSettings> databaseSettings)
        {
            var mongoClient = new MongoClient(
                databaseSettings.Value.ConnectionString);

            var mongoDatabase = mongoClient.GetDatabase(
                databaseSettings.Value.DatabaseName);

            _collection = mongoDatabase.GetCollection<ElekseLog>(
                databaseSettings.Value.CollectionName);
        }
    }

the question is i dont want to store db info in appsettings json file. I want to host this .net core app from IIS so I want to send this configuration info from IIS. Is there a way to achieve this?

CodePudding user response:

One Option is to use the Microsoft.Extensions.Configuration.SystemEnvironment provider so you can set configuration values using environment variables.

You can then set the environment variables on the IIS server to provide the necessary configuration for your app.

Another option would be the Microsoft.Extensions.Configuration.UserSecrets which allows you to store configuration in user locations on the file system instead of the appsettings.json file.

CodePudding user response:

You can replace values from appsettings.json with environment variables by adding ".AddEnvironmentVariables();" in Program.cs

  public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((webhostBuilderContext, configurationbuilder) =>
            {
                configurationbuilder.AddJsonFile("appsettings.json")
                .AddEnvironmentVariables();
            })
            .UseStartup<Startup>();


}

The setup up of environment variables in ISS is decribed here: https://stackoverflow.com/a/36836533/5706893

There is a naming convention for env variables, e.g. for the ConnectionString property your env name should be

DataSource__ConnectionString

More details can be found here https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-7.0

  • Related