You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor Server应用无法从appsettings.json获取连接字符串求助

Blazor Server中获取连接字符串返回null的解决办法

核心问题分析

  • Configuration配置时机错误:你在var app = builder.Build();之后才修改Configuration,此时builder已完成构建,后续配置修改无法生效,必须在Build前完成配置加载。
  • appsettings.json结构错误:ConnectionStrings节点被嵌套在Logging节点内,ASP.NET Core默认仅读取根节点下的ConnectionStrings,嵌套结构无法被识别。
  • GetConnectionString用法错误:该方法参数只需传入连接字符串名称(如"Books"),无需添加"ConnectionStrings:"前缀,方法会自动从根节点的ConnectionStrings下匹配对应配置。

修复后的代码

修复后的Program.cs

using DataAnalyzer.Data;
using DataAnalyzer.Data.Connection;
using DataAnalyzer.Data.Books;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;

var builder = WebApplication.CreateBuilder(args);

// 注册服务
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddSingleton<BooksService>();

// 先获取连接字符串,再构建app
ConnectionHelper.conStr = builder.Configuration.GetConnectionString("Books");

var app = builder.Build();

// 配置HTTP请求管道
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

注:WebApplication.CreateBuilder(args)默认已自动加载appsettings.json、appsettings.{Environment}.json等配置文件,无需手动调用AddJsonFile,除非使用自定义配置路径。

修复后的appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "Books": "data source=MyServer;User ID=TestUser;Password=TestPassword;Persist Security Info=True;initial catalog=Books;MultipleActiveResultSets=True"
  },
  "AllowedHosts": "*"
}

将ConnectionStrings节点从Logging中移出,作为根节点的一级子节点。

额外优化建议:避免静态类存储连接字符串

静态类的方式不利于测试和依赖注入,建议通过依赖注入传递连接或数据库对象:

// Program.cs中注册服务
builder.Services.AddScoped<SqlConnection>(sp => 
    new SqlConnection(builder.Configuration.GetConnectionString("Books")));

在业务服务中通过构造函数注入:

public class BooksService
{
    private readonly SqlConnection _connection;

    public BooksService(SqlConnection connection)
    {
        _connection = connection;
    }

    // 业务逻辑中直接使用_connection即可
}

内容的提问来源于stack exchange,提问作者RKh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 03:49:53