问题描述
我正在使用asp.Net核心Web API 6.0(干净的体系结构项目)。
这是我的appsettings.Production.json和appsettings.Development.json
{
"Tokens": {
"Key": "my-token",
"Issuer": "issuer",
"Audience": "audience",
"ExpirationInMinutes": 1440
},
// removed rest
}
using Microsoft.Extensions.Configuration;
public static IServiceCollection AddTokenAuthentication(this IServiceCollection services, IConfiguration config)
{
var secret = config.GetValue<string>("Tokens:Key"); // this value is null while running in development / production mode.
var key = Encoding.ASCII.GetBytes(secret);
// removed rest
}
在开发/生产环境中运行时终端出错
Unhandled exception. System.ArgumentNullException: String reference not set to an instance of a String. (Parameter 's') at System.Text.Encoding.GetBytes(String s) at Infrastructure.Files.AuthenticationExtension.AddTokenAuthentication(IServiceCollection services, IConfiguration config) in /src/Infrastructure/Files/AuthenticationExtension.cs:line 14 at Infrastructure.DependencyInjection.AddInfrastructure(IServiceCollection services, IConfiguration configuration) in /src/Infrastructure/DependencyInjection.cs:line 75 at Program.<Main>$(String[] args) in/src/WebApi/Program.cs:line 21 Aborted (core dumped)
注意:
如果我像这样硬编码secret
的值
var secret = "my-token";
则项目在两个环境中都运行良好。
在开发和生产环境中运行时,所有环境变量均为空。
GetConnectionString
的错误相同
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<DbContext>(options =>
options.UseNpgsql(
configuration.GetConnectionString("DefaultConnection"), // this is also null while running in both environment.. If I hard-coded then working fine
b => b.MigrationsAssembly(typeof(DbContext).Assembly.FullName))
.EnableSensitiveDataLogging());
// removed rest
}
为什么会发生这种情况? 我的代码中有什么错误吗? 请帮我找出错误?
编辑:
我还尝试将appsettings.Development.json
中的所有内容复制并粘贴到appsettings.json
中
这不起作用。
这是我的 LaunchSettings.json
"WebApi": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"WebApi-Production": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7152;http://localhost:5105",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
}
},
推荐答案
是否在生产环境中设置环境变量ASPNETCORE_ENVIRONMENT=PRODUCTION?
默认情况下,ASP.NET Core将从appsettings.json文件和appsettings.Environment ment.json文件(例如appsettings.Development.json)读取配置。
您可以在生产环境中设置ASPNETCORE_ENVIRONMENT=PRODUCTION,也可以在appsettings.json文件中设置生产配置。
这些文档可能对您有帮助:
- Configuration in ASP.NET Core
- Use multiple environments in ASP.NET Core
-例如-
我的appsettings.json
{
"EFCoreSlowQuery": {
"ServiceName": "json",
"SlowQueryThresholdMilliseconds": 10
}
}
读取代码中的配置:
这篇关于无法在ASP.NET核心Web API 6.0中获取环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!