ASP.NET Core WebAPI 6无法读取配置值,如何修复?
问题描述
正在将ASP.NET Core 3.x版本的自定义JWT Token WebAPI项目迁移至ASP.NET Core WebAPI 6版本,当前遇到配置读取失败的问题,相关配置文件及代码如下:
appsettings.json 配置
{ /* The following identity settings need to be configured before the project can be successfully executed. */ "AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "qualified.domain.name", "TenantId": "22222222-2222-2222-2222-222222222222", "ClientId": "11111111-1111-1111-11111111111111111", "Scopes": "access_as_user", "CallbackPath": "/signin-oidc" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" }, "ConnectionStrings": { "DefaultConnection": "Server=127.0.0.1;Port=5432;Database=acc200;User Id=postgres;Password=postgres;" } }, "AllowedHosts": "*", "AppSettings": { "Key": "986ghgrgtru989ASdsaerew13434545439", "Issuer": "atul1234" } }
开发环境配置文件(原文件名拼写错误)
原文件名为applications.Development.json,内容如下:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" }, "AllowedHosts": "*", "AppSettings": { "Key": "986ghgrgtru989ASdsaerew13434545435", "Issuer": "atul1234" }, "ConnectionStrings": { "DefaultConnection": "Server=127.0.0.1;Port=5432;Database=foo;User Id=postgres;Password=postgres;" } } }
Program.cs 代码
using acc7.Data; using JWTTokenPOC.Helper; using JWTTokenPOC.Service; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Identity.Web; using Microsoft.Identity.Web.Resource; using System.Configuration; using AuthenticationService = JWTTokenPOC.Service.AuthenticationService; namespace acc7 { public class Program { public IConfiguration Configuration { get; } public Program(IConfiguration configuration) { Configuration = configuration; } public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd")); var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql("Server=127.0.0.1;Port=5432;Database=acc200;User Id=postgres;Password=postgres;")); builder.Services.AddControllers(); builder.Services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddCors(); builder.Services.AddScoped<IUserService, UserService>(); builder.Services.AddScoped<JWTTokenPOC.Service.IAuthenticationService, AuthenticationService>(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); app.UseCors(x => x .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); app.UseMiddleware<JwtMiddleware>(); app.MapControllers(); app.Run(); } } }
错误截图

修复步骤
1. 修正配置文件命名错误
ASP.NET Core默认只会识别appsettings.Development.json作为开发环境配置文件,将原applications.Development.json重命名为appsettings.Development.json。
2. 修正配置文件结构错误
ConnectionStrings、AllowedHosts、AppSettings被错误嵌套在Logging节点下,ASP.NET Core配置系统无法正常读取,需移至根节点:
修改后的appsettings.json
{ "AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "qualified.domain.name", "TenantId": "22222222-2222-2222-2222-222222222222", "ClientId": "11111111-1111-1111-11111111111111111", "Scopes": "access_as_user", "CallbackPath": "/signin-oidc" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "ConnectionStrings": { "DefaultConnection": "Server=127.0.0.1;Port=5432;Database=acc200;User Id=postgres;Password=postgres;" }, "AllowedHosts": "*", "AppSettings": { "Key": "986ghgrgtru989ASdsaerew13434545439", "Issuer": "atul1234" } }
修改后的appsettings.Development.json
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "AppSettings": { "Key": "986ghgrgtru989ASdsaerew13434545435", "Issuer": "atul1234" }, "ConnectionStrings": { "DefaultConnection": "Server=127.0.0.1;Port=5432;Database=foo;User Id=postgres;Password=postgres;" } }
3. 修正Program.cs中的配置读取错误
ASP.NET Core 6的静态Main方法无法访问实例属性Configuration,需直接使用builder.Configuration读取配置,同时移除多余的构造函数和System.Configuration引用:
修改后的Program.cs
using acc7.Data; using JWTTokenPOC.Helper; using JWTTokenPOC.Service; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.EntityFrameworkCore; using Microsoft.Identity.Web; using AuthenticationService = JWTTokenPOC.Service.AuthenticationService; namespace acc7 { public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd")); // 从配置文件读取连接字符串 var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(connectionString)); builder.Services.AddControllers(); // 使用builder.Configuration读取AppSettings builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings")); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddCors(); builder.Services.AddScoped<IUserService, UserService>(); builder.Services.AddScoped<JWTTokenPOC.Service.IAuthenticationService, AuthenticationService>(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); app.UseCors(x => x .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); app.UseMiddleware<JwtMiddleware>(); app.MapControllers(); app.Run(); } } }
4. 验证修复效果
重新编译运行项目后:
- 连接字符串会根据当前环境自动读取对应配置文件的值
- AppSettings配置可正常绑定到实体类
- 原编译错误会消失
内容的提问来源于stack exchange,提问作者Đỗ Như Vỹ
相关产品推荐
相关产品推荐

