NetCore 获取appsetting.json 文件中的配置

1. 

using Microsoft.Extensions.Configuration

public
class HomeController : Controller { public IConfiguration _configuration { get; set; } public HomeController(IConfiguration configuration) { _configuration = configuration; } public IActionResult Index() {
//获取 appsettings 中的
ConnectionStrings节点下面的key为 DefaultConnection 的value
var config = _configuration.GetSection("ConnectionStrings:DefaultConnection"); return View(); }

 

 

 

2. 在srartup中写

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();

#region 获取数据库连接字符串


var builder = new ConfigurationBuilder();
builder.SetBasePath(Directory.GetCurrentDirectory());
builder.AddJsonFile("appsettings.json");
var connectionStringConfig = builder.Build();
var connectionString = connectionStringConfig["ConnectionStrings:DefaultConnection"];

services.AddDbContext<EFProjectContext>(options => options.UseMySQL(connectionString));



#endregion 

}

 

posted @ 2018-05-07 14:58  爱坐枫林晚  阅读(521)  评论(0编辑  收藏  举报