我已经从Visual Studio 2022提供的默认模板中创建了一个全新的ASP.NET Core Web API项目(.NET 6)。之后,我在appsettings.json文件中添加了一个配置键,并尝试在
我的appsettings.json文件如下:
控制器代码如下:
在上述方法中,我收到了
更新:
这是在Visual Studio 2022中创建新的ASP.NET Core Web API 针对.NET 6时得到的裸骨项目。当我创建一个针对.NET 5的新项目时,我没有任何问题,因为在那个项目中,
controller
类内部访问它,但是无法访问。我的appsettings.json文件如下:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ProjectName" : "VeryFunny"
}
控制器代码如下:
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly IConfiguration _configuration;
public WeatherForecastController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = _configuration["ProjectName"] // <-- I added this
})
.ToArray();
}
}
在上述方法中,我收到了
null
而不是VeryFunny
字符串,这是一个箭头注释。我认为在.NET 6中合并Startup.cs
类和Program.cs
类之后,IConfiguration
现在很容易获得,但似乎我错了。更新:
这是在Visual Studio 2022中创建新的ASP.NET Core Web API 针对.NET 6时得到的裸骨项目。当我创建一个针对.NET 5的新项目时,我没有任何问题,因为在那个项目中,
Startup.cs
和Porgram.cs
是分开的类,并且Startup
类中已经注入了IConfiguration
实例,然而在.NET 6中却不是这样。有一篇现有的SO问题问同样的问题,但该问题及其答案集中于.NET 6之前的.NET实现,例如.NET Core 2.x、.NET 5等。我的问题是.NET 6特定的。
AppSettings
父元素下;而你的ProjectName
则位于根目录下... 根据惯例,你会想要将其嵌套在AppSettings
下面,但是也可以在没有它的情况下通过编程方式访问它。 - JohnLBevan