简体   繁体   中英

How to use appsettings.json in Asp.net core 6 Program.cs file

I'm trying to access appsettings.json in my Asp.net core v6 application Program.cs file, but in this version of.Net the Startup class and Program class are merged together and the using and another statements are simplified and removed from Program.cs. In this situation, How to access IConfiguration or how to use dependency injection for example?

Code

Here is my default Program.cs that Asp.net 6 created for me

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
});

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasketAPI v1"));
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

For example, I want to use appsettings.json instead of hard typed connectionstring in this line:

options.Configuration = "localhost:6379";

While the examples above work, the way to do this is the following:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration["Redis"];
});

The WebApplicationBuilder has a configuration object as a property that you can use.

appsettings.json is included by default, you can use it directly. If you want to include files explicitly, you can include them like this

builder.Configuration.AddJsonFile("errorcodes.json", false, true);

And dependency injection like this

builder.Services.AddDbContext<>() // like you would in older .net core projects.

In case that we have in appsettings

"settings": {
    "url": "myurl",
    "username": "guest",
    "password": "guest"
  }

and we have the class

public class Settings
    {
        public string Url { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }

we can use also

var settings = builder.Configuration.GetSection("Settings").Get<Settings>();

var url = settings.Url;

etc....

Assuming an appsettings.json

{
    "RedisCacheOptions" : {
        "Configuration": "localhost:6379"
    }
}

There is nothing stopping you from building a configuration object to extract the desired settings.

IConfiguration configuration = new ConfigurationBuilder()
                            .AddJsonFile("appsettings.json")
                            .Build();

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options => {
    options.Configuration = configuration["RedisCacheOptions:Configuration"];
});

//...

Create a class:

public class RedisCacheOptions
{
    public string Configuration { get; set; }
}

And then, in your program.cs , do the following:

var redisCacheOptions = new RedisCacheOptions();
builder.Configuration.GetSection(nameof(RedisCacheOptions)).Bind(redisCacheOptions);

You can now access the configuration info by simply saying:

redisCacheOptions.Configuration

Now say you had a nested structure in appSettings.json like so:

"AuthenticationConfiguration": {
  "JwtBearerConfiguration": {
    "Authority": "https://securetoken.google.com/somevalue",
    "TokenValidationConfiguration": {
      "Issuer": "https://securetoken.google.com/somevalue",
      "Audience": "somevalue"
    }
  }
}

Then, your class structure would be something like:

public class AuthenticationConfiguration
{
    public JwtBearerConfiguration JwtBearerConfiguration { get; set; } = new JwtBearerConfiguration();
}

public class JwtBearerConfiguration
{
    public string Authority { get; set; }

    public TokenValidationConfiguration TokenValidationConfiguration { get; set; } =
        new TokenValidationConfiguration();
}

public class TokenValidationConfiguration
{
    public string Issuer { get; set; }
    public string Audience { get; set; }
}

With this, if you were to do:

var authConf = new AuthenticationConfiguration();
builder.Configuration.GetSection(nameof(AuthenticationConfiguration)).Bind(authConf);

Then in your program, you could access values as:

AuthenticationConfiguration.JwtBearerConfiguration.Authority

This approach allows you to do away with magic strings, plus you get IntelliSense, so it's a win-win.

In Program.cs, try this code:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

ConfigurationManager configuration = builder.Configuration;

var rabbitMQSection = Configuration.GetSection("RabbitMQ");
var rabbitMQConnectionUrl = rabbitMQSection["ConnectionUrl"];

where the appsettings.json file is:

"AllowedHosts": "*",
"RabbitMQ": {
    "ConnectionUrl": "amqp://guest:guest@localhost:5672/"
}

Solved: Get appsetting value in program.css in dotnet6

appsettings.json

  "AllowedHosts": "*",
  "ServiceUrls": {
  "EmployeeAPI": "https://localhost:44377/" },

Program.cs

var builder = WebApplication.CreateBuilder(args);    
var provider = builder.Services.BuildServiceProvider();
var configuration = provider.GetService<IConfiguration>();
SD.EmployeeAPIBase = configuration.GetValue<string>("ServiceUrls:EmployeeAPI");

Class static variable:

public static class SD //Static Details
{
    public static string EmployeeAPIBase { get; set; }     
}

Finally, use the full URL

URL = SD.EmployeeAPIBase + "api/EmpContact/GetGovernates"

In .NET 6

appSettings.json

{
  "Authentication": {
    "CookieAuthentication": {
      "LoginPath": "/Security/Login"
    }
  },
  "TestValue" :  "Testing data"
}

Program.cs

var builder = WebApplication.CreateBuilder(args);

var testValue = builder.Configuration.GetValue<string>("TestValue");

var cookieAuthenticationLoginPath = builder.Configuration.GetValue<string>("Authentication:CookieAuthentication:LoginPath");

This is how you can get appsettings.json values in Program.cs file. Here is sample

appsettings.json file

  "Jwt": {
    "Key": "ThisismySecretKey",
    "Issuer": "www.joydipkanjilal.net"
  },

Get values in Program.cs file

var app = builder.Build();
var config = app.Configuration;
var key = config["Jwt:Key"];
var issuer = config["Jwt:Issuer"];

Retrieve appsettings.json section values via Injection

appsettings.json section:

{
  "AppSettings": {
    "Key": "Value"
  }
}

AppSettings.cs :

public class AppSettings
{
    public string Key { get; set; }
}

Program.cs :

builder.Services.AddOptions();
builder.Services.Configure<AppSettings>(
    builder.Configuration.GetSection("AppSettings"));

Inject IOptions<> via constructor:

private readonly AppSettings _appSettings;

public HomeController(
    IOptions<AppSettings> options)
{
    _appSettings = options.Value;
}

You can read the setting value from your appsettings.json file like this, in Program.cs :

var dbConnectionString = builder.Configuration.GetSection("ConnectionStrings:TestDbConnection").Value;

Considering the setting looks something like this in your appsettings.json file:

  "ConnectionStrings": {
    "TestDbConnection": ""
  }

In addition to the @dimmits & @Sarwarul Rizvi answares, if you would like to read a plain key value pair instead to map to a complex object, you can use:

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Information",
      "Microsoft.AspNetCore.SpaProxy": "Information",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedOrigins": "https://localhost:444/YourApplicationUri;https://localhost:7211",
  "ConnectionStrings": {
    "Default": "Connection String details"
  }
}

program.cs

ConfigurationManager configuration = builder.Configuration;
var allowedOrigins = configuration.GetValue<string>("AllowedOrigins");

This can be used for example to config Cors

if (!String.IsNullOrEmpty(allowedOrigins))
{
    builder.Services.AddCors(options =>
    {
        var origins = allowedOrigins.Split(";");

        options.AddPolicy("CorsPolicy", policy =>
        {
            policy.AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
                .WithOrigins(origins);
        });
    });
}

Later and below app.UseRouting();

app.UseCors("CorsPolicy");

你可以使用这个方法

builder.Configuration.GetConnectionString("<connection string name>");

Since my application was a consol .NET Core 6 application, I had to install a nuget packages first:

  • Microsoft.Extensions.Hosting
  • Microsoft.Extensions.Configuration

Then add their associated usings:

  • using Microsoft.Extensions.Configuration;
  • using Microsoft.Extensions.Configuration;

Then I added this code to the Program.cs file

// Build a config object, using env vars and JSON providers.
IConfiguration config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddEnvironmentVariables()
    .Build();
Settings settings = config.GetRequiredSection("Settings").Get<Settings>();

I have a Settings.cs class to accept the values from my appsettings.json file

Settings.cs

internal class Settings
{
    public static string Setting1 { get; set; }
    public static string Setting2 { get; set; }
    public static string Setting3 { get; set; }

}

And AppSettings.json

"Settings": {
    "Setting1": "yep",
    "Setting2": "nope",
    "Setting3": "kjkj"
  }

This resource from Microsoft helped me navigate the new .NET Core 6 architecture

https://docs.microsoft.com/en-us/dotnet/core/extensions/configuration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM