ASP.NET Core 3.X IConfiguration取值
程序员文章站
2023-12-28 19:10:28
...
当从配置中取设置的变量值的话,可以从appsettings.json/appsettings.Development.json/自定义的类以及环境变量中取
从appsettings.json中获取
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env,
IConfiguration configuration,
IWelcome iWelcome)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//app.UseWelcomePage();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
var welcome = configuration["welcome"];
//var welcome = iWelcome.GetMessage();
await context.Response.WriteAsync(welcome);
});
});
}
在appsetting.json中增加一个变量welcome
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"welcome": "hello welcom from appsetting.json"
}
此时,点击测试,可以显示从appsettings.json中配置的变量
从appsettings.Development.json中取值
如果appsetting.json和appsettings.Development.json都存在同一变量的值,那么最终会从appsettings.Development.json中获取
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"welcome": "hello welcom from appsetting.json"
}
appsettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"welcome": "hello world from appseting from development"
}
测试显示结果
从自定义的类中获取变量值
自定义接口
public interface IWelcome
{
string GetMessage();
}
接口实现
public class welcome:IWelcome
{
public string GetMessage()
{
return "hello world from service";
}
}
启动服务注册,如果不进行注册,是无法直接使用依赖注入的功能的
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IWelcome, welcome>();
}
然后在IConfiguration中将这个接口注入
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env,
IConfiguration configuration,
IWelcome iWelcome)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//app.UseWelcomePage();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
//var welcome = configuration["welcome"];
var welcome = iWelcome.GetMessage();
await context.Response.WriteAsync(welcome);
});
});
}
然后测试
还可以通过电脑上的环境变量来获取,这里就不演示了。
推荐阅读
-
ASP.NET Core 3.X IConfiguration取值
-
ASP.NET Core 3.x 并发限制
-
使用ASP.NET Core 3.x 构建 RESTful API - 5.1 输入验证
-
asp.net core 3.x 微信小程序登录库(也可用于abp)
-
asp.net core 3.x 通用主机是如何承载asp.net core的-上
-
asp.net core 3.x 模块化开发之HostingStartup
-
使用ASP.NET Core 3.x 构建 RESTful API - 3.4 内容协商
-
ASP.NET Core 3.x 并发限制的实现代码
-
使用ASP.NET Core 3.x 构建 RESTful API - 4.3 HTTP 方法的安全性和幂等性
-
asp.net core 3.x 通用主机原理及使用