我很困惑 ASP.NET Core MVC 是如何工作的。我需要建立从 Oracle 数据库到我的 ASP.NET Core 项目的连接。我将连接字符串存储在
appsettings.json
中,但它到此结束。我不知道如何从 json 文件获取它并在我的控制器中使用它。
我希望有人能指出我在这方面的正确方向。
这是我的
appsettings.json
:
"ConnectionStrings": {
"DBConn": "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=XXXXXX)(PORT=0000))(CONNECT_DATA=(SERVICE_NAME=test.sample.test)));User Id=USER_TST;Password=UserPass;"
}
以下内容展示了如何从 ASP.NET Core Web 应用程序(模型-视图-控制器) (.NET 8) 项目中的 appsettings.json 检索数据库连接字符串。
appSettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DBConnectionStr": "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=HOSTSERVER) (PORT=0001))(CONNECT_DATA=(SERVICE_NAME=TEST.TEST.TEST)));User Id=Test_ID;Password=PassID;"
}
}
选项1:
创建一个类(名称:DBConnection)
public class DBConnection
{
public const string SectionName = "ConnectionStrings";
//name from appsettings.json
public string? DBConnectionStr { get; set; }
}
然后在HomeController.cs:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private string? _dbConnStr = string.Empty;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
//create new instance
WebApplicationBuilder builder = WebApplication.CreateBuilder();
builder.Services.Configure<DBConnection>(builder.Configuration.GetSection(DBConnection.SectionName));
//build
WebApplication app = builder.Build();
//get connection string
_dbConnStr = app.Configuration.GetConnectionString("DBConnectionStr");
Debug.WriteLine($"dbConn: {_dbConnStr}");
}
//Additional code/methods here
}
选项2:
安装/下载 NuGet 包:
Microsoft.Extensions.Configuration.Json
添加使用指令:
using Microsoft.Extensions.Configuration.Json;
HomeController.cs:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private string? _dbConnStr = string.Empty;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
//create new instance
Microsoft.Extensions.Configuration.ConfigurationBuilder builder = new ConfigurationBuilder();
builder.SetBasePath(Directory.GetCurrentDirectory());
builder.AddJsonFile("appsettings.json");
IConfigurationRoot configuration = builder.Build();
_dbConnStr = configuration.GetConnectionString("DBConnectionStr");
Debug.WriteLine($"_connStr: {_dbConnStr}");
}
//Additional code/methods here
}
资源: