注册配置实例
Registers a configuration instance which TOptions will bind against.
AppSettings.cs
public class AppSettings
{
public const string Key = nameof(AppSettings);
public string ConnectionString { get; set; }
public int Port { get; set; }
}
Program.cs
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
// AppSettings appSettings = builder.Configuration.GetSection(AppSettings.Key).Get<AppSettings>()!;
// Console.WriteLine(appSettings.Port);
// Console.WriteLine(appSettings.ConnectionString);
使用方式1
// 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
AppSettings appSettings = builder.Configuration.GetSection(AppSettings.Key).Get<AppSettings>()!;
Console.WriteLine(appSettings.Port);
Console.WriteLine(appSettings.ConnectionString);
WeatherForecastController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace AspDemo.Server.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing",
"Bracing",
"Chilly",
"Cool",
"Mild",
"Warm",
"Balmy",
"Hot",
"Sweltering",
"Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
private readonly AppSettings _appSettings;
// 👇👇👇👇👇👇👇👇👇👇👇👇👇
public WeatherForecastController(ILogger<WeatherForecastController> logger , IOptions<AppSettings> appSettings)
{
_logger = logger;
// 👇👇👇👇👇👇👇👇👇👇👇👇
_appSettings = appSettings.Value;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
// 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
System.Console.WriteLine(_appSettings.ConnectionString);
System.Console.WriteLine(_appSettings.Port);
return Enumerable
.Range(1, 5)
.Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}