04. Asp.Net Core 3.x 笔记 配置文件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了04. Asp.Net Core 3.x 笔记 配置文件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2197字,纯文字阅读大概需要4分钟。
内容图文
![04. Asp.Net Core 3.x 笔记 配置文件](/upload/InfoBanner/zyjiaocheng/631/31d9cce5439e479bafb29b756763b4a9.jpg)
目录
配置文件优先级
1.appsettings.json
2.appsettings.{xxxx}.json,比如: appsettings.Development.json
3.环境变量
4.命令行
越靠后,优先级越高,将覆盖前者
添加自定义配置
appsettings.json
:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Three": {
"BoldDepartmentEmployeeCountThreshold": 30
}
}
获取及其使用配置项:
Startup.cs
public class Startup
{
private readonly IConfiguration configuration;
public Startup(IConfiguration configuatuion)
{
configuration = configuatuion;
var three = configuration["Three:BoldDepartmentEmployeeCountThreshold"];
}
自定义配置对象及其获取
- 自定义配置对象
ThreeOptions
,
public class ThreeOptions
{
public int BoldDepartmentEmployeeCountThreshold { get; set; }
public int MyProperty { get; set; }
}
- 注册配置对象
public class Startup
{
private readonly IConfiguration configuration;
public Startup(IConfiguration configuatuion)
{
configuration = configuatuion;
//var three = configuration["Three:BoldDepartmentEmployeeCountThreshold"];
}
//注册服务
public void ConfigureServices(IServiceCollection services)
{
...
services.Configure<ThreeOptions>(configuration.GetSection("Three"));
}
- 在
xxxControler
中使用:
public class DepartmentController : Controller
{
private readonly IOptions<ThreeOptions> threeOptions;
public DepartmentController(IDepartmentService departmentService, IOptions<ThreeOptions> threeOption)
{
this.departmentService = departmentService;
}
- 在Views使用
xxx.cshtml
中使用:
@model Three.Models.Department
@inject Microsoft.Extensions.Options.IOptions<Three.ThreeOptions> options
...
@if (Model.EmployeeCount > options.Value.BoldDepartmentEmployeeCountThreshold)
{
...
}
...
自定义配置文件
myconfig.json
:
{
"Three": {
"BoldDepartmentEmployeeCountThreshold": 1000
}
}
Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, configBuilder) =>
{
//configBuilder.Sources.Clear();
configBuilder.AddJsonFile("myconfig.json");
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
myconfig.json 会覆盖 appsettings.json 相同的配置项
内容总结
以上是互联网集市为您收集整理的04. Asp.Net Core 3.x 笔记 配置文件全部内容,希望文章能够帮你解决04. Asp.Net Core 3.x 笔记 配置文件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。