如何读取 ASP .NET Core Razor Pages 中的连接字符串
How to read connection string in ASP .NET Core Razor Pages
我不知道如何在 ASP .NET Core 中检索连接字符串。我花了两天时间尝试了所有不同的东西,但无法正常工作。
我试过以下方法:
- 使用 ConfigurationManager.AppSettings 计数 returns 0
- 使用 ConfigurationManager.ConnectionStrings[].ConnectionString - 唯一存在的连接字符串是 .\SQLEXPRESS(必须在 ConnectionStrings[] 中使用索引而不是字符串), 指定连接名称导致对象引用未设置错误
- 尝试使用 WebConfigurationManager 找不到如何添加它。我试过 System.Web.Configuration、NuGet 包、参考资料。
- 使用 IConfiguration 和依赖注入 - 我不知道如何读取连接字符串(如何在模型中引用控制器并读取 "xxx" 连接字符串)
ConfigurationManager.ConnectionStrings["SupplierDB"].ConnectionString
// NullReferenceException: Object reference not set to an instance of an object.
ConfigurationManager.ConnectionStrings[0].ConnectionString
// data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
ConfigurationManager.AppSettings.Count.ToString();
// Returns 0
我在 appsettings.json 和 web.config 中指定了相同的连接字符串。有人能给我指明正确的方向吗,因为我目前完全迷失了,因为什么都不起作用。
appsettings.json
{
"ConnectionStrings": {
"CustomerDB": "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Customer_Db;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",
"SupplierDB": "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Supplier_Db;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="CustomerDB" providerName="System.Data.SqlClient" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Customer_Db;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"/>
<add name="SupplierDB" providerName="System.Data.SqlClient" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Supplier_Db;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"/>
</connectionStrings>
</configuration>
您可以像这样创建一个 AppSettings
class,方法是将您的 appsettings.json 复制到 QuickType:
public class AppSettings
{
public static ConnectionStrings ConnectionStrings { get; set; }
public static Logging Logging { get; set; }
public static string AllowedHosts { get; set; }
}
public class ConnectionStrings
{
public string CustomerDb { get; set; }
public string SupplierDb { get; set; }
}
public class Logging
{
public LogLevel LogLevel { get; set; }
}
public class LogLevel
{
public string Default { get; set; }
public string Microsoft { get; set; }
public string MicrosoftHostingLifetime { get; set; }
}
然后在Startup
:
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)
{
Configuration.Get<AppSettings>();
services.AddControllersWithViews();
}
我使用 static
来方便访问,而不是通过 DI 注入 AppSettings
。
或者,如果您不想将它们全部放在一个 class 中,请查看 Microsoft 的 Options pattern。
确保安装了以下 NuGets:
Microsoft.Extensions.Configuration;
Microsoft.Extensions.Configuration.Json;
//Microsoft.Extensions.Configuration.UserSecrets; //Microsoft.Extensions.Configuration.EnvironmentVariables;
- 生成以下内容class:
使用Microsoft.Extensions.Configuration;
使用 System.IO;
public static class CustomConfiguration
{
public static IConfigurationRoot config;
public static void BuildConfiguration()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
//.AddUserSecrets(Assembly.GetExecutingAssembly(), optional: true, reloadOnChange: true)
//.AddEnvironmentVariables();
config = builder.Build();
}
}
然后,从任何你喜欢的地方调用 Subject 方法
CustomConfiguration.BuildConfiguration();
string connectionString = CustomConfiguration.config.GetConnectionString("CustomerDB");
您可以在 appsettings.json 中获取连接字符串值,如下所示:
对于 Mvc:
public class HomeController : Controller
{
public readonly IConfiguration _configuration;
public HomeController(IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult Index()
{
string CustomerDBConnectionString = _configuration.GetConnectionString("CustomerDB");
string SupplierDBConnectionString = _configuration.GetConnectionString("SupplierDB");
return View();
}
}
对于 Razor 页面:
public class IndexModel : PageModel
{
public readonly IConfiguration _configuration;
public IndexModel(IConfiguration configuration)
{
_configuration = configuration;
}
public void OnGet()
{
string CustomerDBConnectionString = _configuration.GetConnectionString("CustomerDB");
string SupplierDBConnectionString = _configuration.GetConnectionString("SupplierDB");
}
}
结果:
我不知道如何在 ASP .NET Core 中检索连接字符串。我花了两天时间尝试了所有不同的东西,但无法正常工作。
我试过以下方法:
- 使用 ConfigurationManager.AppSettings 计数 returns 0
- 使用 ConfigurationManager.ConnectionStrings[].ConnectionString - 唯一存在的连接字符串是 .\SQLEXPRESS(必须在 ConnectionStrings[] 中使用索引而不是字符串), 指定连接名称导致对象引用未设置错误
- 尝试使用 WebConfigurationManager 找不到如何添加它。我试过 System.Web.Configuration、NuGet 包、参考资料。
- 使用 IConfiguration 和依赖注入 - 我不知道如何读取连接字符串(如何在模型中引用控制器并读取 "xxx" 连接字符串)
ConfigurationManager.ConnectionStrings["SupplierDB"].ConnectionString
// NullReferenceException: Object reference not set to an instance of an object.
ConfigurationManager.ConnectionStrings[0].ConnectionString
// data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
ConfigurationManager.AppSettings.Count.ToString();
// Returns 0
我在 appsettings.json 和 web.config 中指定了相同的连接字符串。有人能给我指明正确的方向吗,因为我目前完全迷失了,因为什么都不起作用。
appsettings.json
{
"ConnectionStrings": {
"CustomerDB": "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Customer_Db;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",
"SupplierDB": "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Supplier_Db;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="CustomerDB" providerName="System.Data.SqlClient" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Customer_Db;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"/>
<add name="SupplierDB" providerName="System.Data.SqlClient" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Supplier_Db;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"/>
</connectionStrings>
</configuration>
您可以像这样创建一个 AppSettings
class,方法是将您的 appsettings.json 复制到 QuickType:
public class AppSettings
{
public static ConnectionStrings ConnectionStrings { get; set; }
public static Logging Logging { get; set; }
public static string AllowedHosts { get; set; }
}
public class ConnectionStrings
{
public string CustomerDb { get; set; }
public string SupplierDb { get; set; }
}
public class Logging
{
public LogLevel LogLevel { get; set; }
}
public class LogLevel
{
public string Default { get; set; }
public string Microsoft { get; set; }
public string MicrosoftHostingLifetime { get; set; }
}
然后在Startup
:
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)
{
Configuration.Get<AppSettings>();
services.AddControllersWithViews();
}
我使用 static
来方便访问,而不是通过 DI 注入 AppSettings
。
或者,如果您不想将它们全部放在一个 class 中,请查看 Microsoft 的 Options pattern。
确保安装了以下 NuGets:
Microsoft.Extensions.Configuration;
Microsoft.Extensions.Configuration.Json;
//Microsoft.Extensions.Configuration.UserSecrets; //Microsoft.Extensions.Configuration.EnvironmentVariables;
- 生成以下内容class:
使用Microsoft.Extensions.Configuration; 使用 System.IO;
public static class CustomConfiguration
{
public static IConfigurationRoot config;
public static void BuildConfiguration()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
//.AddUserSecrets(Assembly.GetExecutingAssembly(), optional: true, reloadOnChange: true)
//.AddEnvironmentVariables();
config = builder.Build();
}
}
然后,从任何你喜欢的地方调用 Subject 方法
CustomConfiguration.BuildConfiguration();
string connectionString = CustomConfiguration.config.GetConnectionString("CustomerDB");
您可以在 appsettings.json 中获取连接字符串值,如下所示:
对于 Mvc:
public class HomeController : Controller
{
public readonly IConfiguration _configuration;
public HomeController(IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult Index()
{
string CustomerDBConnectionString = _configuration.GetConnectionString("CustomerDB");
string SupplierDBConnectionString = _configuration.GetConnectionString("SupplierDB");
return View();
}
}
对于 Razor 页面:
public class IndexModel : PageModel
{
public readonly IConfiguration _configuration;
public IndexModel(IConfiguration configuration)
{
_configuration = configuration;
}
public void OnGet()
{
string CustomerDBConnectionString = _configuration.GetConnectionString("CustomerDB");
string SupplierDBConnectionString = _configuration.GetConnectionString("SupplierDB");
}
}
结果: