注册配置实例
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")); |
| |
| |
| |
使用方式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(); |
| } |
| } |
| } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
2022-09-06 pip-离线安装第三方包
2022-09-06 flask restful demo from github