您如何以与其前身 webforms 相同的风格阅读 appsettings.json?
How do you read from appsettings.json in the same style as it's predecessor, webforms?
在 WebForms
中,我们将有一个 web.config
文件,我们可以 ConfigurationManager.AppSettings["SomeKey"];
从键值对中检索值。
我刚刚在 .NET 5.0
开始了一个项目,似乎没有简单的方法来做一些看似微不足道的事情?
我在网上查看过有关如何使用 @
表示法从 .cshtml
文件访问 appsettings.json
中的这些密钥的教程,但没有成功。
appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"MyKey": "wwwwwwwwwww"
}
Index.cshtml:
<h1>
Title - @ConfigurationManager.AppSettings["MyKey"];
</h1>
以上说明了我正在努力实现的目标,有没有一种简单的方法可以做到这一点而不是创建 类 等,因为我似乎无法遵循他们的示例。
To access configuration settings 在 .NET 项目的视图中,您应该能够使用 @
注释。这是通过将配置注入页面来完成的:
@page
@model Test5Model
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
Configuration value for 'MyKey': @Configuration["MyKey"]
以此appsettings.json为例:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Test": "Hello World",
"ConnectionStrings": {
"SomeContext": "SomeConnectionStringProperties"
},
"SectionOne": {
"SectionOneTestVal": "SomeTestValue"
}
}
为了访问 Test
键,它只是 @Configuration["Test"]
而要访问 SectionOne
部分中的 SectionOneTestVal
“键”,你会做像 Configuration.GetSection("SectionOne")["SectionOneTestVal"]
:
因此将其添加到视图中:
<p>@Configuration["Test"]</p>
<p>@Configuration.GetSection("SectionOne")["SectionOneTestVal"]</p>
...将产生:
有关更多信息和示例,另请查看 dependency injection into views。
在 WebForms
中,我们将有一个 web.config
文件,我们可以 ConfigurationManager.AppSettings["SomeKey"];
从键值对中检索值。
我刚刚在 .NET 5.0
开始了一个项目,似乎没有简单的方法来做一些看似微不足道的事情?
我在网上查看过有关如何使用 @
表示法从 .cshtml
文件访问 appsettings.json
中的这些密钥的教程,但没有成功。
appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"MyKey": "wwwwwwwwwww"
}
Index.cshtml:
<h1>
Title - @ConfigurationManager.AppSettings["MyKey"];
</h1>
以上说明了我正在努力实现的目标,有没有一种简单的方法可以做到这一点而不是创建 类 等,因为我似乎无法遵循他们的示例。
To access configuration settings 在 .NET 项目的视图中,您应该能够使用 @
注释。这是通过将配置注入页面来完成的:
@page
@model Test5Model
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
Configuration value for 'MyKey': @Configuration["MyKey"]
以此appsettings.json为例:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Test": "Hello World",
"ConnectionStrings": {
"SomeContext": "SomeConnectionStringProperties"
},
"SectionOne": {
"SectionOneTestVal": "SomeTestValue"
}
}
为了访问 Test
键,它只是 @Configuration["Test"]
而要访问 SectionOne
部分中的 SectionOneTestVal
“键”,你会做像 Configuration.GetSection("SectionOne")["SectionOneTestVal"]
:
因此将其添加到视图中:
<p>@Configuration["Test"]</p>
<p>@Configuration.GetSection("SectionOne")["SectionOneTestVal"]</p>
...将产生:
有关更多信息和示例,另请查看 dependency injection into views。