欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

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

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

IConfiguration

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

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

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

通過GetValue方法獲取

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

GetValue?法讀取對象,會報異常

通過GetSection方法獲取

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

讀取對象

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

使用委托來配置選項

先定義?個實體:

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}";
});

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

相關文章

最新評論