配置文件,是一个每个应用服务程序常用的功能,从原来的终端应用时代,到现在的元宇宙时代,配置都是很悠然自得的存在。asp.net core提供了强大的配置文件访问机制,不管是MVC API还是MiniAPI,使用方式都是相同的。

  框架默认的配置文件是:appsettings.json,可以以json的格式存放自己复杂的配置:

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ExamDatabase": "server=.;database=Exam;uid=sa;pwd=sa;"
},
"AppInfo": {
"Name": "Mini & Powerful",
"Version": "v1.0.0",
"Author": {
"Architect": "桂素伟-A",
"Programmer": "桂素伟-P",
"Designer": "桂素伟-D"
},
"Features": [ "Learn MiniAPI", "Architect Element" ]
}
}

简单取值

var architect = builder.Configuration.GetSection("AppInfo:Author:Architect").Value;
var features1=builder.Configuration.GetSection("AppInfo:Features:1").Value;

用record绑定

record

public record AppInfoRecord(string? Name, string? Version, AuthorRecord? Author, string[]? Features);
public record AuthorRecord(string? Architect, string? Programmer, string? Designer);

绑定

var authorRecord = new AuthorRecord(null, null, null);
var appInfoRecord = new AppInfoRecord(null, null, authorRecord, null);
builder.Configuration.GetSection("AppInfo").Bind(appInfoRecord);

结果

.NET6之MiniAPI(四):配置_取值

 用class绑定
class

public class AppInfo
{
public string? Name { get; set; }
public string? Version { get; set; }
public Author? Author { get; set; }
public string[]? Features { get; set; }
}
public class Author
{
public string? Architect { get; set; }
public string? Programmer { get; set; }
public string? Designer { get; set; }
}

绑定

var appInfo = new AppInfo();
builder.Configuration.GetSection("AppInfo").Bind(appInfo);

结果

.NET6之MiniAPI(四):配置_取值_02

 

  用record和class绑定各有优势,record定义的时间代码简单,绑定要复杂一些,class正好相反,定义要复杂一些,绑定时简单。

从IConfiguration中获取配置

可以在路由方法中获取配置信息

app.MapGet("/getappinfo", (IConfiguration config) =>
{
return config.GetSection("AppInfo:Name").Value;
});

从路由中取配置文件
首选注入

var authorRecord = new AuthorRecord(null, null, null);
var appInfoRecord = new AppInfoRecord(null, null, authorRecord, null);
builder.Configuration.GetSection("AppInfo").Bind(appInfoRecord);
builder.Services.AddSingleton(appInfoRecord);

取配置数据

app.MapGet("/appinfo", (AppInfoRecord appinfo) =>
{
return appinfo;
});

结果

.NET6之MiniAPI(四):配置_配置文件_03

读取其他格式的配置文件
myconfig.ini

[iniconfig]
key1=value1
key2=value2

加载配置文件,并取值

builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddIniFile("myconfig.ini",
optional: true,
reloadOnChange: true);
});

var key1=builder.Configuration.GetSection("iniconfig:key1").Value;


  想要更快更方便的了解相关知识,可以关注微信公众号 


.NET6之MiniAPI(四):配置_ico_04