.net core 2.0 读取配置文件
asp .net
1.引用Microsoft.Extensions.Configuration
2.在Startup中注入服务
public static IConfiguration Configuration { get; private set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
//添加服务
services.AddUrlResolve(Configuration);
}
扩展方法AddUrlResolve如下
/// <summary>
/// 拓展方法
/// </summary>
public static class Extensions
{
/// <summary>
/// 为了保留IConfiguration
/// </summary>
/// <param name="services"></param>
/// <param name="config"></param>
public static void AddUrlResolve(this IServiceCollection services, IConfiguration config)
{
services.Add(new ServiceDescriptor(typeof(UrlResolveService), typeof(UrlResolveService), ServiceLifetime.Singleton));
//读取配置文件
UrlResolveService.ApiUrl = config["ApiUrl"];
UrlResolveService.AuthorityUrl = config["AuthorityUrl"];
}
}
/// <summary>
/// 读取配置文件的服务
/// </summary>
public class UrlResolveService
{
public static string AuthorityUrl { get; set; }
public static string ApiUrl { get; set; }
public string GetAuthorityUrl()
{
return AuthorityUrl;
}
public string GetApiUrl()
{
return ApiUrl;
}
}
3.使用UrlResolveService服务
public async Task<IActionResult> Call(UrlResolveService urlResolveService)
{
//API对应网址
var apiUrl = urlResolveService.GetApiUrl();
//......
}
4.配置文件
{
//授权网址
"AuthorityUrl": "http://localhost:5000/",
//API网址
"ApiUrl": "http://localhost:5001/",
}
控制台(console)
1.引用
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json
2.创建appsettings.json
{
"YourKey": "YourValue",
}
并设置为生成时复制到输出目录
3.关键代码
var builder = new ConfigurationBuilder()
//保证执行文件下有json文件
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true, true)
.Build();
var yourValue = config["YourKey"];
参考资料
How to use Configuration API in .net core console application
示例代码
学习技术最好的文档就是【官方文档】,没有之一。
还有学习资料【Microsoft Learn】、【CSharp Learn】、【My Note】。
如果,你认为阅读这篇博客让你有些收获,不妨点击一下右下角的【推荐】按钮。
如果,你希望更容易地发现我的新博客,不妨点击一下【关注】。