【.NetCore】读取appsetting.json中的配置参数

文档

https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-10.0

配置

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "NovelSetting": {
    "PageSize": 15
  }
}

方法1

配置相关

public class NovelSettingOption
{
	public int PageSize { get; set; }
}

services.Configure<NovelSettingOption>(Configuration.GetSection("NovelSetting"));

使用

private readonly NovelSettingOption _novelSettingOption;

public WeatherForecastController(IOptions<NovelSettingOption> novelSettingOption)
{
	_novelSettingOption = novelSettingOption.Value;
}

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
	int size1 = _novelSettingOption.PageSize;

	var rng = new Random();
	return Enumerable.Range(1, 5).Select(index => new WeatherForecast
	{
		Date = DateTime.Now.AddDays(index),
		TemperatureC = rng.Next(-20, 55),
		Summary = Summaries[rng.Next(Summaries.Length)]
	})
	.ToArray();
}

方法2

配置相关

public class AppSettings
{
	private static IConfigurationSection appSection = null;

	public static string GetAppSeting(string key)
	{
		if (appSection.GetSection(key) != null)
		{
			return appSection.GetSection(key).Value;
		}
		else
		{
			return default;
		}
	}

	public static void SetAppSetting(IConfigurationSection section)
	{
		appSection = section;
	}
}

AppSettings.SetAppSetting(Configuration.GetSection("NovelSetting"));

使用

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
	string size2 = AppSettings.GetAppSeting("PageSize");

	var rng = new Random();
	return Enumerable.Range(1, 5).Select(index => new WeatherForecast
	{
		Date = DateTime.Now.AddDays(index),
		TemperatureC = rng.Next(-20, 55),
		Summary = Summaries[rng.Next(Summaries.Length)]
	})
	.ToArray();
}
posted @ 2020-06-02 14:19  我有我奥妙  阅读(2408)  评论(0)    收藏  举报