1、使用appsettings.json文件配置
1)添加引用
需要引用Microsoft.Extensions.Configuration
、Microsoft.Extensions.Configuration.FileExtensions
和Microsoft.Extensions.Configuration.Json
,
可以通过NuGet包管理器在Visual Studio中安装Microsoft.Extensions.Configuration、Microsoft.Extensions.Configuration.FileExtensions
和Microsoft.Extensions.Configuration.Json
。打开项目,右键点击项目,选择“Manage NuGet Packages”,搜索找到并安装。
相关文档:VS(Visual Studio)中Nuget的使用
2)命令空间
using Microsoft.Extensions.Configuration;
using System.IO;
3)配置代码
var builder = WebApplication.CreateBuilder(args);
string connString = builder.Configuration.GetConnectionString("DefaultConnection");
或
builder.Services.AddDbContext<YourContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
或
var objBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appSettings.json", optional: true, reloadOnChange: true);
IConfiguration conManager = objBuilder.Build();
var my = conManager.GetConnectionString("DefaultConnection");
4)appsettings.json文件中添加配置
"ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true" },
2、使用环境变量配置连接字符串
在应用程序的运行环境中设置环境变量,将连接字符串作为环境变量的值。然后,在Startup.cs
文件的ConfigureServices
方法中,通过依赖注入的方式将连接字符串注入到DbContext中,例如,
public void ConfigureServices(IServiceCollection services)
{
// ...
string connectionString = Environment.GetEnvironmentVariable("DefaultConnection");
services.AddDbContext<YourDbContext>(options =>
options.UseSqlServer(connectionString));
// ...
}