亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

ASP.NET讀取配置文件的多種方式詳解

 更新時(shí)間:2025年02月14日 10:47:17   作者:code-Study  
ASP.NET?Core?是一個(gè)模塊化、高性能的框架,它使用依賴注入來構(gòu)建應(yīng)用程序的各個(gè)組件,在?ASP.NET?Core?中,配置文件扮演著至關(guān)重要的角色,下面我們就來看看ASP.NET讀取配置文件有哪些方式吧

ASP.NET Core項(xiàng)?默認(rèn)的配置?件是appsettings.json,創(chuàng)建項(xiàng)?時(shí)就會?動(dòng)?成這個(gè)文件,我們可以將?些配置信息存放在這個(gè)配置?件中,這樣做的好處是當(dāng)我們修改配置?件 時(shí),不在需要重啟應(yīng)?,可以實(shí)現(xiàn)熱更新。

{
 "Logging": {
 "LogLevel": {
 "Default": "Information",
 "Microsoft.AspNetCore": "Warning"
 }
 },
 "AllowedHosts": "*",
 "msg": "hello world"
}

IConfiguration

個(gè)路由終結(jié)點(diǎn)來演?如何讀取這個(gè)配置

app.MapGet("config", (IConfiguration configuration) =>
{
 return configuration["msg"] + "_" +
     configuration["Logging:LogLevel:Default"];
});

通過IOC注?IConfiguration對象,我們就可以訪問不同節(jié)點(diǎn)的配置了,如果是單層節(jié)點(diǎn), 通過configuration[“msg”]的?式進(jìn)?訪問,如果是多層級,則通過 configuration[“Logging:LogLevel:Default”]來訪問

通過GetValue方法獲取

app.MapGet("config", (IConfiguration configuration) =>
{
     return configuration.GetValue<string>("msg");
});

GetValue?法讀取對象,會報(bào)異常

通過GetSection方法獲取

app.MapGet("config", (IConfiguration configuration) =>
{
     return configuration.GetSection("msg").Value;
});

讀取對象

app.MapGet("config", (IConfiguration configuration) =>
{
     return configuration.GetSection("Person").Get<Person>();
});

使用委托來配置選項(xiàng)

先定義?個(gè)實(shí)體:

public class Person
{
     public string Name { get;set; }
     public int Age { get;set; }
}

配置如下:

"Person": {
 "Name": "張三",
 "Age": 18
}

注冊配置:

builder.Services.Configure<Person>
(builder.Configuration.GetSection("Person"));

使?配置:

app.MapGet("config", (IOptions<Person> options) =>
{
     return $"{options.Value.Name},{options.Value.Age}";
});

到此這篇關(guān)于ASP.NET讀取配置文件的多種方式詳解的文章就介紹到這了,更多相關(guān)ASP.NET讀取配置文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論