ASP.NET 核心如何在第一个 运行 时间初始化连接字符串?

ASP.NET Core how to init connection string in first run-time?

我正在构建一个企业应用程序,我希望第一次使用 运行 网站时能够选择要连接的 SQL 服务器,以及该服务器中的数据库。在那之后,应用程序总是 运行 在配置上像正常 asp.net 核心应用程序一样。

我知道连接字符串存储在 appsettings.json 中,所以我考虑在选择此配置后在 运行 时更改它的值,但经过大量搜索后我认为这是不可能的.

建议有什么方法可以做到这一点?

您必须在 Program.cs

中加载 appsettings.json 文件
public static void Main(string[] args)
{
    IConfigurationRoot configuration = new ConfigurationBuilder()
      .AddJsonFile("appsettings.json", optional: false) 
      .Build();

    string conStr = configuration.GetConnectionString("DefaultConnection");

    // your code


    var host = WebHost.CreateDefaultBuilder();

    host.Run();
} 

appsettings.json 添加到 ConfigurationBuilder 时将 reloadOnChange 设置为真:

var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
    .AddEnvironmentVariables();

然后为连接字符串

创建一个class
public class ConnectionString
{
    public string Default {get; set;}
}

并且在ConfigureServices方法中:

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.Configure<ConnectionString>(Configuration.GetSection("ConnectionStrings"));
}

现在可以通过依赖注入获得此配置。

public class HomeController : Controller  
{
    private readonly ConnectionString _connectionString;

    public HomeController(IOptionsSnapshot<ConnectionString> connectionString)
    {
        _connectionString = connectionString.Value;
    }
}

IOptionsSnapshot可以在更改时重新加载配置数据。

有关 Configuration 的更多信息。

确保在连接到 SQL 服务器数据库之前安装了以下 NuGet 包。

首先,您必须在 appsettings.json 中创建连接字符串,如下所示

"ConnectionStrings": {
"DefaultConnection": "Server=DESKTOP-O57GSNN\MSSQLSERVERNEW,Database=BookListRazor;Trusted_Connection=True;MultipleActiveResultSets=True"},

Here, DefaultConnection is connection Name you are going to use.Please provide any meaningful name you want and it will be use when configuring.Also provide Server Name from SQL Server Management Studio(see the picture below) and Provide a name for your database (Will be created).

然后创建 ApplicationDbContext.cs 文件并输入以下代码

 public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
            
    }

    public DbSet<Book> Book { get; set; }
}

Book is the Model in my App.

最后使用 Startup.cs 文件中 ConfigureServices 方法中的 SQL 服务器配置对其进行配置。

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddRazorPages().AddRazorRuntimeCompilation();
    }

DefaultConnection is connection Name which was already mentioned in appsettings.json