如何在 Asp.net 核心6 Program.cs 文件中使用 appsetings.json

我试图在我的 Asp.net 核心 v6应用程序 Program.cs 文件中访问 appsetings.json,但是在这个版本的。Net Startup 类和 Program 类合并在一起,using 语句和其他语句被简化并从 Program.cs 中删除。在这种情况下,如何访问 iConfiguration 或如何使用依赖注入?

密码

这是 Asp.net 6为我创建的默认 Program.cs

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();

例如,我想在这一行中使用 appsetings.json 而不是硬类型的 Connectionstring:

options.Configuration = "localhost:6379";
122968 次浏览

假设是 appsettings.json

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

没有什么可以阻止您构建配置对象来提取所需的设置。

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"];
});


//...

Json 是默认包含的,您可以直接使用它。 如果要显式地包含文件,可以像下面这样包含它们

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

像这样的依赖注入

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

虽然上面的例子很有效,但是做到这一点的方法如下:

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

WebApplicationBuilder有一个配置对象作为可以使用的属性。

Create a class:

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

然后,在你的 program.cs中,做以下动作:

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

您现在可以访问配置信息,只需说:

redisCacheOptions.Configuration

现在假设你在 appSettings.json中有一个 嵌套的结构,如下所示:

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

然后,你的类结构应该是这样的:

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; }
}

用这个,如果你要做:

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

然后在您的程序中,您可以访问如下值:

AuthenticationConfiguration.JwtBearerConfiguration.Authority

这种方法允许您去掉神奇的字符串,另外还可以获得 IntelliSense,因此这是一种双赢。

解决: 在 dotnet6中的 Program.css 中获取 appset 值

Appsettings.json

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

程序

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

类静态变量:

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

最后,使用完整的 URL

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

您可以像下面这样从 appsettings.json文件中读取设置值,在 Program.cs中:

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

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

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

在.NET 6中

AppSettings.json

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

程序

var builder = WebApplication.CreateBuilder(args);


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


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

以防我们在应用程序设置中

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

我们还有课

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

我们也可以使用

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


var url = settings.Url;

etc....

在 Program.cs 中,尝试下面的代码:

var builder = WebApplication.CreateBuilder(args);


// Add services to the container.


ConfigurationManager configuration = builder.Configuration;


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

appsettings.json文件所在的位置:

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

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"
}
}


程序

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

这可以用于例如配置 Cors

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


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

后面和下面的应用程序

app.UseCors("CorsPolicy");

您可以使用此方法

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

通过 Injection检索 appsettings.json节值

appsettings.json部分:

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

返回文章页面

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

返回文章页面

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;
}

因为我的应用程序是一个 consol. NET Core 6应用程序,所以我必须首先安装一个 nuget 包:

  • 微软,扩展,主机
  • 微软,扩展,配置

然后添加它们的相关用法:

  • 使用微软。扩展。配置;
  • 使用微软。扩展。配置;

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>();

我有一个 Settings.cs 类来接受 appsetings.json 文件中的值

设置

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


}

还有 AppSettings.json

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

这个来自微软的资源帮助我导航新的.NETCore6架构

Https://learn.microsoft.com/en-us/dotnet/core/extensions/configuration

这就是如何在 Program.cs文件中获取 appsettings.json值的方法

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

获取 Program.cs文件中的值

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