如何读取 ASP .NET Core Razor Pages 中的连接字符串

How to read connection string in ASP .NET Core Razor Pages

我不知道如何在 ASP .NET Core 中检索连接字符串。我花了两天时间尝试了所有不同的东西,但无法正常工作。

我试过以下方法:

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");
    }
}

结果: