我真的很难从 appsettings.json 文件中获取 ConnectionString。我已经查看了很多示例,但大多数都使用实体框架和/或使用较旧的 StartUp.cs 示例。我的应用程序没有使用这两个选项之一。目前我的 Void Main 看起来像这样。
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
builder.Services.AddRazorPages();
builder.Services.AddSingleton<IConfiguration>(configuration);
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseStaticFiles();
app.UseRouting();
app.MapRazorPages();
app.Run();
}
这是我的 DataAccess 文件,我正在其中尝试读取连接字符串。
public class DataAccess
{
private static string connectionstring;
private readonly IConfiguration _configuration;
public DataAccess(IConfiguration configuration)
{
_configuration = configuration;
connectionstring = _configuration.GetConnectionString("P51InvConnection");
}
public static async Task<DataTable> ExecuteDataTableAsync(
string storedProcedureName)
{
return await ExecuteDataTableAsync(storedProcedureName, null!);
}
public static async Task<DataTable> ExecuteDataTableAsync(
string storedProcedure, params SqlParameter[] parameters)
{
DataTable dt = default;
Console.WriteLine(connectionstring);
try
{
await Task.Run(() =>
{
Console.WriteLine();
using SqlConnection conn = new(connectionstring);
conn.Open();
using SqlCommand cmd = new(storedProcedure, conn);
cmd.CommandTimeout = 3;
cmd.CommandType = CommandType.StoredProcedure;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
}
using SqlDataAdapter da = new(cmd);
dt = new DataTable();
da.Fill(dt);
});
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return dt; //?? throw new Exception("DataTable empty or null");
}
public static SqlParameter Parameter(
string parameterName, object parameterValue)
{
SqlParameter param = new()
{
ParameterName = parameterName,
Value = parameterValue
};
return param;
}
}
我遇到的错误是
ConnectionString 属性尚未初始化
在
ExecuteDataTableAsync
方法中。另外,我已经验证我的连接字符串名为 P51InvConnection
是 appsettings.json
。
进行编辑以包含 appsettings.json 文件的内容。
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"P51InvConnection": "Data Source=xxx;User ID=xxx;Password=xxx;Connect Timeout=30;Encrypt=False;"
}
}
再编辑一次。这是第一次使用 DataAccess 类调用数据库,但我认为问题不在这里,因为如果我将应用程序设置中的连接字符串复制并粘贴到 SqlConnection 初始化中,这确实有效。
public static async Task<List<Entry>> EntryList()
{
List<Entry> entryList = new();
DataTable dt = await DataAccess.ExecuteDataTableAsync("[dbo].[OpenTransfer_Select]");
foreach (DataRow row in dt.Rows)
{
Entry entry = new()
{
Id = Convert.IsDBNull(row[IdColumn])
? 0
: Convert.ToInt32(row[IdColumn]),
UserId = Convert.IsDBNull(row[UserIdColumn])
? string.Empty
: Convert.ToString(row[UserIdColumn]),
ItemNumber = Convert.IsDBNull(row[ItemNumberColumn])
? string.Empty
: Convert.ToString(row[ItemNumberColumn]),
EntryDate = Convert.IsDBNull(row[TransferDateColumn])
? Convert.ToDateTime("1/1/1900")
: Convert.ToDateTime(row[TransferDateColumn])
};
entryList.Add(entry);
}
return entryList;
}
问题是静态方法无法通过注入访问配置。但如果你尝试创建一个新的配置生成器,它就会起作用。
public static async Task<DataTable> ExecuteDataTableAsync(
string storedProcedure, params SqlParameter[] parameters)
{
var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var connectionstring = configuration.GetConnectionString("P51InvConnection");
Console.WriteLine(connectionstring);
}