第一次接触asp.net core 所以就想写个程序,那么第一步就是要读取数据库的连接地址,以前都是利用ConfigurationManager.AppSettings["url"]; 直接读取,而现在变成json文件了,怎么读取?上网搜了一些资料,有很多关于读取的,但是我的好像有一些不太一样,总之记录一下吧。
appsettings.json 文件
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AppSettings": {
"ConnectionString": "PORT=5432;DATABASE=Demo;HOST=localhost;PASSWORD=root;USER ID=postgres"
},
"AllowedHosts": "*"
}
读取appsettings.json我感觉有两种方式:先说第一种吧
新建个类
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System.IO;
namespace WebApplication2.Data
{
public class ConfigManager
{
public static IConfiguration Configuration { get; set; }
static ConfigManager()
{
//ReloadOnChange = true 当appsettings.json被修改时重新加载
#region 方式1(ok)
Configuration = new ConfigurationBuilder()
.Add(new JsonConfigurationSource
{
Path = "appsettings.json",
ReloadOnChange = true
}).Build();
#endregion
#region 方式2(ok)
//Configuration = new ConfigurationBuilder()
// .SetBasePath(Directory.GetCurrentDirectory())
// .AddJsonFile("appsettings.json").Build();
#endregion
}
}
}
然后在 Controller 里面通过json中的路径直接就可以读取 string appId = ConfigManager.Configuration["AppSettings:ConnectionString"];
第二种方式:感觉有点麻烦
新建一个module
public class AppSettings
{
public string ConnectionString { get; set; }
}
然后在Startup类中的Startup函数中增加 如下所示,红色为新加的
public Startup(IConfiguration configuration)
{
Configuration = new ConfigurationBuilder().
Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true }).Build();
//Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddControllersWithViews();
}
然后在Controller类中这么写,红色的为后加的
private readonly ILogger<ContentController> _logger;
public AppSettings appsettings;
public ContentController(ILogger<ContentController> logger, IOptions<AppSettings> setting)
{
_logger = logger;
appsettings = setting.Value;
}
public IActionResult Index()
{
string connectionstring = appsettings.ConnectionString;//这样就可以获取了
return View();
}
项目路径地址 https://github.com/liulangfashi/-appsettings.json