作者:恋苦尘雪77 | 来源:互联网 | 2023-10-14 14:10
获取ConnectionStrings节点数据appsettings.json{ConnectionStrings:{DEVDbConn:Server**;Integra
获取ConnectionStrings节点数据
//appsettings.json
{
"ConnectionStrings": {
//DEV
"DbConn": "Server=**;Integrated Security=no;User ID=**;PWD=**;initial catalog=DB**;MultipleActiveResultSets=true;Max Pool Size=1024;Min Pool Size=10;Pooling=true;"
//QA
//PROD
},
"ErrorPage": "/Error/Error",
"Environment": "DEV"
}
//startup.cs
public Startup(IConfiguration configuration) //依赖注入
{
_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)
{
string _conn;
//config db
try
{
//GetSection("Environment")获取Environment节点的数据
if (_configuration.GetSection("Environment").Value.Equals("PROD", StringComparison.OrdinalIgnoreCase))
{
var service = new DecryptService("ProjectICE_Portal");
_cOnn= service.Decrypt(_configuration.GetConnectionString("DbConn"));//加密获取节点数据
}
else
{
_cOnn= _configuration.GetConnectionString("DbConn");//非加密
}
}
catch (Exception ex)
{
throw new Exception($"Database connection initialization failed: {ex.Message}{ex.StackTrace}");
}
}
第二种比较实用的方法
//Appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning"
}
},
"AllowedHosts": "*",
"student": {
"name": "小明",
"age": 17,
"classname": "5班"
}
}
//新建一个实体类 实体类的属性和配置文件的配置项一致
public class student
{
public string name { get; set; }
public int age { get; set; }
// public string classname { get; set; }
}
//Startup.cs
//services.AddOptions(); 这两个必须在AddMvc上面
services.Configure(Configuration.GetSection("student"));
services.AddMvc();
//Controller 依赖注入 using Microsoft.Extensions.Options;
public class OneController : Controller
{
private readonly IOptions _log;
public OneController(IOptions logs)
{
_log = logs;
}
public IActionResult Index()
{
var a = _log.Value;
ViewBag.a = a.name; //"小明"
return View();
}
}
.Net Core中获取appsettings.json中的节点数据的相关教程结束。