Tuesday, 24 May 2022

.Net Core - Get appsettings..json data in class or controller

 .Net Core applications contains appsettings.json, it contains major configurations related to application, Environment, Database, etc.

Some config key values will be different depends on the environment, example Development, Staging, Production. In this scenario we need maintain key values depends on environment. 

Let see how to overcome this issue, Example DB configuration will be different for every environment so we need maintain different   appsettings.<Environment>.json file like child of appsettings.json.

Based on Environment flag it will override the values i,e take vales from  appsettings.<Environment>.json override in  appsettings.json at runtime.

1.Set Environment Variable

Properties folder -> launchSettings.json file we can set environment values.

Example Set it as Development

{
    "$schema": "https://json.schemastore.org/launchsettings.json",
    "iisSettings": {
      "windowsAuthentication": false,
      "anonymousAuthentication": true,
      "iisExpress": {
        "applicationUrl": "http://localhost:8320",
        "sslPort": 44311
      }
    },
    "profiles": {
      "SolidPrinciples": {
        "commandName": "Project",
        "dotnetRunMessages": true,
        "launchBrowser": true,
        "launchUrl": "swagger",
        "applicationUrl": "https://localhost:7033;http://localhost:5033",
        "environmentVariables": {
          "ASPNETCORE_ENVIRONMENT": "Development"
        }
      },
      "IIS Express": {
        "commandName": "IISExpress",
        "launchBrowser": true,
        "launchUrl": "swagger",
        "environmentVariables": {
          "ASPNETCORE_ENVIRONMENT": "Development"
        }
      }
    }
  }
 

appsetings.json

{
    "Logging": {
      "LogLevel": {
        "Default": "Information",
        "Microsoft.AspNetCore": "Warning"
      }
    },
    "AllowedHosts": "*",
    "Environment": "Prod",
    "ConnectionStrings": {
      ///we need to alter corresponding actual DB connection string.
      "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=Prod;"
    }
  }
 

appsetings.Development.json

{
    "Environment": "Development",
    "ConnectionStrings": {
      ///we need to alter corresponding actual DB connection string.
      "DefaultConnection": "Server=(Development)\\MSSQLLocalDB;Database=Development;"
    }
  }
 

appsetings.Staging.json

{
    "Environment": "Staging",
    "ConnectionStrings": {
      ///we need to alter corresponding actual DB connection string.
      "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=Staging;"
    }
 }
 

In API code we try to consume Environment key from appsetings.

    [Route("api/[controller]")]
    [ApiController]
    public class AppRegionController : ControllerBase
    {
        private readonly ILogger<WeatherForecastController> _logger;
        private readonly IConfiguration _configuration;
        public AppRegionController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
        }
        [HttpGet(Name = "ApplicationRegion")]
        public string Get()
        {
            /// it will return value is Development from appsetings.development.json
            var env = _configuration["Environment"];
            var db= _configuration["ConnectionStrings:DefaultConnection"];
            return env;
        }
    }

Now run application and read through api call ,values we will get like below.

Request URL

https://localhost:7033/api/AppRegion

Server response

CodeDetails
200
Response body
Download
Development
Response headers
 content-type: text/plain; charset=utf-8  date: Tue,24 May 2022 10:43:52 GMT  server: Kestrel 

Now change environment to staging like below

{
    "$schema": "https://json.schemastore.org/launchsettings.json",
    "iisSettings": {
      "windowsAuthentication": false,
      "anonymousAuthentication": true,
      "iisExpress": {
        "applicationUrl": "http://localhost:8320",
        "sslPort": 44311
      }
    },
    "profiles": {
      "SolidPrinciples": {
        "commandName": "Project",
        "dotnetRunMessages": true,
        "launchBrowser": true,
        "launchUrl": "swagger",
        "applicationUrl": "https://localhost:7033;http://localhost:5033",
        "environmentVariables": {
          "ASPNETCORE_ENVIRONMENT": "Staging"
        }
      },
      "IIS Express": {
        "commandName": "IISExpress",
        "launchBrowser": true,
        "launchUrl": "swagger",
        "environmentVariables": {
          "ASPNETCORE_ENVIRONMENT": "Staging"
        }
      }
    }
  }

Call same API we will get Staging as response.

Request URL

https://localhost:7033/api/AppRegion

Server response

CodeDetails
200
Response body
Download
Staging

Note:

In case keys not exist in region config but Exist in appsetings.json then it will take it from appsetings.json

Both files exist same then it will override based on environment.

When we deploy all appsettings file exist in build folder.

Environment Based We can enable/Disable feature

Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
if(app.Environment.IsStaging())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();






No comments:

Post a Comment