我正在尝试访问我的 Asp.net core v6 应用程序 Program.cs 文件中的 appsettings.json,但在此版本的 .Net 中,Startup 类和 Program 类合并在一起,并且 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(); …Run Code Online (Sandbox Code Playgroud) 在.NET Core Console应用程序上,我正在尝试将自定义appsettings.json文件中的设置映射到自定义配置类.
我在线查看了几个资源,但无法使.Bind扩展方法有效(我认为它适用于asp.net应用程序或以前版本的.Net Core,因为大多数示例都表明了这一点).
这是代码:
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
//this is a custom configuration object
Configuration settings = new Configuration();
//Bind the result of GetSection to the Configuration object
//unable to use .Bind extension
configuration.GetSection("MySection");//.Bind(settings);
//I can map each item from MySection manually like this
settings.APIBaseUrl = configuration.GetSection("MySection")["APIBaseUrl"];
//what I wish to accomplish is to map the section to my Configuration object
//But …Run Code Online (Sandbox Code Playgroud) 我正在使用 .NET Core 3.1 创建一个控制台应用程序,我想要一个 appsettings json 在执行开始时加载所有环境、路径、变量...,然后从其他库类中获取值。我已经使用 appsettings json 中包含的数据创建了一个“设置”类。这是我在教程中已经看到的,但我无法获得任何价值。
//Start.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
}
//Settings.cs
public class Settings
{
public ConnectionStrings ConnectionStrings { get; set; }
public Logging Logging { get; set; }
public AppSettings AppSettings { get; set; } …Run Code Online (Sandbox Code Playgroud)