怪物奇妙物语

宇宙无敌超级美少男的怪物奇妙物语

首页 新随笔 联系 管理
  819 随笔 :: 0 文章 :: 2 评论 :: 16万 阅读

注册配置实例

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();
}
}
}
posted on   超级无敌美少男战士  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
历史上的今天:
2022-09-06 pip-离线安装第三方包
2022-09-06 flask restful demo from github
点击右上角即可分享
微信分享提示