如何在 Asp.net 核心 6 Program.cs 文件中使用 appsettings.json
How to use appsettings.json in Asp.net core 6 Program.cs file
我正在尝试访问我的 Asp.net 核心 v6 应用程序 Program.cs 文件中的 appsettings.json,但在此版本的 .Net 中,启动 class 和程序 class 被合并在一起,using 和 another 语句被简化并从 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();
例如,我想在这一行中使用 appsettings.json 而不是硬类型的连接字符串:
options.Configuration = "localhost:6379";
假设 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"];
});
//...
默认包含appsettings.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
有一个配置对象作为您可以使用的 属性。
创建 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"
}
}
}
那么,您的 class 结构将类似于:
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 中的应用设置值
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 静态变量:
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;
考虑到您的 appsettings.json
文件中的设置看起来像这样:
"ConnectionStrings": {
"TestDbConnection": ""
}
在 .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");
如果我们在应用程序设置中有
"settings": {
"url": "myurl",
"username": "guest",
"password": "guest"
}
我们有 class
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;
等....
在 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/"
}
除了@dimmits 和@Sarwarul Rizvi answares,如果你想读取一个普通的键值对而不是映射到一个复杂的对象,你可以使用:
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");
这可以用来配置 Cors
if (!String.IsNullOrEmpty(allowedOrigins))
{
builder.Services.AddCors(options =>
{
var origins = allowedOrigins.Split(";");
options.AddPolicy("CorsPolicy", policy =>
{
policy.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.WithOrigins(origins);
});
});
}
以后及以下 app.UseRouting();
app.UseCors("CorsPolicy");
你可以用这个方法
builder.Configuration.GetConnectionString("<connection string name>");
我正在尝试访问我的 Asp.net 核心 v6 应用程序 Program.cs 文件中的 appsettings.json,但在此版本的 .Net 中,启动 class 和程序 class 被合并在一起,using 和 another 语句被简化并从 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();
例如,我想在这一行中使用 appsettings.json 而不是硬类型的连接字符串:
options.Configuration = "localhost:6379";
假设 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"];
});
//...
appsettings.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
有一个配置对象作为您可以使用的 属性。
创建 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"
}
}
}
那么,您的 class 结构将类似于:
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 中的应用设置值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 静态变量:
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;
考虑到您的 appsettings.json
文件中的设置看起来像这样:
"ConnectionStrings": {
"TestDbConnection": ""
}
在 .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");
如果我们在应用程序设置中有
"settings": {
"url": "myurl",
"username": "guest",
"password": "guest"
}
我们有 class
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;
等....
在 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/"
}
除了@dimmits 和@Sarwarul Rizvi answares,如果你想读取一个普通的键值对而不是映射到一个复杂的对象,你可以使用:
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");
这可以用来配置 Cors
if (!String.IsNullOrEmpty(allowedOrigins))
{
builder.Services.AddCors(options =>
{
var origins = allowedOrigins.Split(";");
options.AddPolicy("CorsPolicy", policy =>
{
policy.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.WithOrigins(origins);
});
});
}
以后及以下 app.UseRouting();
app.UseCors("CorsPolicy");
你可以用这个方法
builder.Configuration.GetConnectionString("<connection string name>");