[英]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.我正在尝试在我的 Asp.net 核心 v6 应用程序 Program.cs 文件中访问 appsettings.json,但是在这个版本的 .Net 中,Startup class 和 Program class 被合并在一起,使用和另一个语句被简化并从 Program.cs 中删除. In this situation, How to access IConfiguration or how to use dependency injection for example?在这种情况下,如何访问 IConfiguration 或如何使用依赖注入?
Here is my default Program.cs that Asp.net 6 created for me这是 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();
For example, I want to use appsettings.json instead of hard typed connectionstring in this line:例如,我想在此行中使用 appsettings.json 而不是硬类型连接字符串:
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. WebApplicationBuilder
有一个配置对象作为您可以使用的属性。
appsettings.json is included by default, you can use it directly. appsettings.json 默认包含,可以直接使用。 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如果我们在 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.... ETC....
Assuming an appsettings.json假设一个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:然后,在您的program.cs
中,执行以下操作:
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:现在假设您在appSettings.json
中有一个嵌套结构,如下所示:
"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.这种方法可以让您摆脱魔术字符串,再加上您获得 IntelliSense,因此这是双赢的。
In Program.cs, try this code:在 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"];
where the appsettings.json
file is: appsettings.json
文件在哪里:
"AllowedHosts": "*",
"RabbitMQ": {
"ConnectionUrl": "amqp://guest:guest@localhost:5672/"
}
Solved: Get appsetting value in program.css in dotnet6已解决:在dotnet6的program.css中获取appsetting值
appsettings.json应用设置.json
"AllowedHosts": "*",
"ServiceUrls": {
"EmployeeAPI": "https://localhost:44377/" },
Program.cs程序.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
URL = SD.EmployeeAPIBase + "api/EmpContact/GetGovernates"
In .NET 6在 .NET 6 中
appSettings.json appSettings.json
{
"Authentication": {
"CookieAuthentication": {
"LoginPath": "/Security/Login"
}
},
"TestValue" : "Testing data"
}
Program.cs程序.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.这就是您在 Program.cs 文件中获取 appsettings.json 值的方法。 Here is sample这是样本
appsettings.json
file appsettings.json
文件
"Jwt": {
"Key": "ThisismySecretKey",
"Issuer": "www.joydipkanjilal.net"
},
Get values in Program.cs
file获取Program.cs
文件中的值
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
部分值
appsettings.json
section: appsettings.json
部分:
{
"AppSettings": {
"Key": "Value"
}
}
AppSettings.cs
: AppSettings.cs
:
public class AppSettings
{
public string Key { get; set; }
}
Program.cs
: Program.cs
:
builder.Services.AddOptions();
builder.Services.Configure<AppSettings>(
builder.Configuration.GetSection("AppSettings"));
Inject IOptions<>
via constructor:通过构造函数注入IOptions<>
:
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
:您可以像这样在Program.cs
中从appsettings.json
文件中读取设置值:
var dbConnectionString = builder.Configuration.GetSection("ConnectionStrings:TestDbConnection").Value;
Considering the setting looks something like this in your appsettings.json
file:考虑到appsettings.json
文件中的设置如下所示:
"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:除了@dimmits 和@Sarwarul Rizvi answares,如果你想读取一个普通的键值对而不是映射到一个复杂的对象,你可以使用:
appsettings.json应用设置.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程序.cs
ConfigurationManager configuration = builder.Configuration;
var allowedOrigins = configuration.GetValue<string>("AllowedOrigins");
This can be used for example to config Cors这可以用于例如配置 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.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:由于我的应用程序是一个 consol .NET Core 6 应用程序,我必须先安装一个 nuget 包:
Then add their associated usings:然后添加它们的相关用途:
Then I added this code to the Program.cs file然后我将此代码添加到 Program.cs 文件中
// 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 class 来接受我的 appsettings.json 文件中的值
Settings.cs设置.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和 AppSettings.json
"Settings": {
"Setting1": "yep",
"Setting2": "nope",
"Setting3": "kjkj"
}
This resource from Microsoft helped me navigate the new .NET Core 6 architecture来自 Microsoft 的此资源帮助我了解新的 .NET Core 6 架构
https://docs.microsoft.com/en-us/dotnet/core/extensions/configuration https://docs.microsoft.com/en-us/dotnet/core/extensions/configuration
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.