如何从 ASP.NET Core 中的 .json 文件读取 AppSettings 值
How to read AppSettings values from a .json file in ASP.NET Core
我已经在文件 appsettings/Config 中设置了我的 AppSettings 数据。json 如下所示:
{
"AppSettings": {
"token": "1234"
}
}
我在网上搜索了如何从 .json 文件中读取 AppSettings 值,但没有得到任何有用的信息。
我试过:
var configuration = new Configuration();
var appSettings = configuration.Get("AppSettings"); // null
var token = configuration.Get("token"); // null
我知道 ASP.NET 4.0 可以做到这一点:
System.Configuration.ConfigurationManager.AppSettings["token"];
但是我如何在 ASP.NET Core 中执行此操作?
这有一些波折。我修改了这个答案,使其与 ASP.NET Core 2.0 保持同步(截至 2018 年 2 月 26 日)。
这主要取自the official documentation:
要在 ASP.NET 应用程序中使用设置,建议您仅在应用程序的 Startup
class 中实例化 Configuration
。然后,使用选项模式访问各个设置。假设我们有一个如下所示的 appsettings.json
文件:
{
"MyConfig": {
"ApplicationName": "MyApp",
"Version": "1.0.0"
}
}
我们有一个代表配置的 POCO 对象:
public class MyConfig
{
public string ApplicationName { get; set; }
public int Version { get; set; }
}
现在我们在Startup.cs
中构建配置:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
}
请注意,appsettings.json
将在 .NET Core 2.0 中默认注册。如果需要,我们还可以为每个环境注册一个 appsettings.{Environment}.json
配置文件。
如果我们想将我们的配置注入我们的控制器,我们需要在运行时注册它。我们这样做是通过 Startup.ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}
然后我们像这样注入它:
public class HomeController : Controller
{
private readonly IOptions<MyConfig> config;
public HomeController(IOptions<MyConfig> config)
{
this.config = config;
}
// GET: /<controller>/
public IActionResult Index() => View(config.Value);
}
全 Startup
class:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}
}
首先:
Microsoft.Framework.ConfigurationModel 的程序集名称和命名空间已更改为 Microsoft.Framework.Configuration。所以你应该使用:
例如
"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"
作为 project.json
中的依赖项。如果您没有安装 7,请使用 beta5 或 6。
然后你可以在 Startup.cs
.
中做这样的事情
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddEnvironmentVariables();
Configuration = configurationBuilder.Build();
}
如果您随后想从 config.json 中检索一个变量,您可以使用以下命令立即获取它:
public void Configure(IApplicationBuilder app)
{
// Add .Value to get the token string
var token = Configuration.GetSection("AppSettings:token");
app.Run(async (context) =>
{
await context.Response.WriteAsync("This is a token with key (" + token.Key + ") " + token.Value);
});
}
或者您可以像这样创建一个名为 AppSettings 的 class:
public class AppSettings
{
public string token { get; set; }
}
并像这样配置服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
//mvc options
});
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
然后通过例如访问它像这样的控制器:
public class HomeController : Controller
{
private string _token;
public HomeController(IOptions<AppSettings> settings)
{
_token = settings.Options.token;
}
}
他们只是不断地改变东西——刚刚更新了 Visual Studio 并让整个项目炸弹,在恢复的道路上,新的方式看起来像这样:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
我一直漏掉这一行!
.SetBasePath(env.ContentRootPath)
如果你只是想获取代币的价值,那么使用
Configuration["AppSettings:token"]
对于 .NET Core 2.0,情况发生了一些变化。启动构造函数将 Configuration 对象作为参数,因此不需要使用 ConfigurationBuilder
。这是我的:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<StorageOptions>(Configuration.GetSection("AzureStorageConfig"));
}
我的POCO是上面提到的StorageOptions
对象:
namespace FictionalWebApp.Models
{
public class StorageOptions
{
public String StorageConnectionString { get; set; }
public String AccountName { get; set; }
public String AccountKey { get; set; }
public String DefaultEndpointsProtocol { get; set; }
public String EndpointSuffix { get; set; }
public StorageOptions() { }
}
}
配置实际上是我的 appsettings.json
文件的一个小节,名为 AzureStorageConfig
:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;",
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=fictionalwebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"AzureStorageConfig": {
"AccountName": "fictionalwebapp",
"AccountKey": "Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==",
"DefaultEndpointsProtocol": "https",
"EndpointSuffix": "core.windows.net",
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=fictionalwebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
}
}
我唯一要补充的是,由于构造函数已经更改,我没有测试是否需要做一些额外的事情来加载 appsettings.<environmentname>.json
而不是 appsettings.json
.
我怀疑这是个好习惯,但它在本地有效。如果我 publish/deploy(到 IIS Web 服务)失败,我会更新它。
第 1 步 - 将此程序集添加到 class 的顶部(在我的例子中,控制器 class):
using Microsoft.Extensions.Configuration;
第 2 步 - 添加此内容或类似内容:
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
第 3 步 - 通过执行此操作调用密钥的值(returns 字符串):
config["NameOfYourKey"]
只是为了补充 Yuval Itzchakov 的回答。
你可以加载没有构建器功能的配置,你可以直接注入它。
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
对于 .NET Core 2.0,您可以简单地:
在 appsettings.json 中声明你的 key/value 对:
{
"MyKey": "MyValue"
}
在startup.cs注入配置服务,使用服务获取值
using Microsoft.Extensions.Configuration;
public class Startup
{
public void Configure(IConfiguration configuration,
... other injected services
)
{
app.Run(async (context) =>
{
string myValue = configuration["MyKey"];
await context.Response.WriteAsync(myValue);
});
这是"cheating"吗?我刚刚在 Startup class 中将我的配置设为静态,然后我可以从其他任何地方访问它:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public static IConfiguration Configuration { get; set; }
以下适用于控制台应用程序;
安装以下 NuGet 包 (.csproj
);
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0-preview2-35157" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0-preview2-35157" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0-preview2-35157" />
</ItemGroup>
在根级别创建 appsettings.json
。右键单击它并 "Copy to Output Directory" as "Copy if newer".
示例配置文件:
{
"AppConfig": {
"FilePath": "C:\temp\logs\output.txt"
}
}
Program.cs
configurationSection.Key
和 configurationSection.Value
将具有配置属性。
static void Main(string[] args)
{
try
{
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
// configurationSection.Key => FilePath
// configurationSection.Value => C:\temp\logs\output.txt
IConfigurationSection configurationSection = configuration.GetSection("AppConfig").GetSection("FilePath");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
除了现有的答案之外,我想提一下,为了简单起见,有时 扩展方法 对于 IConfiguration
可能很有用。
我在 appsettings.json 中保留了 JWT 配置,因此我的扩展方法 class 如下所示:
public static class ConfigurationExtensions
{
public static string GetIssuerSigningKey(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:SecurityKey");
return result;
}
public static string GetValidIssuer(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:Issuer");
return result;
}
public static string GetValidAudience(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:Audience");
return result;
}
public static string GetDefaultPolicy(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Policies:Default");
return result;
}
public static SymmetricSecurityKey GetSymmetricSecurityKey(this IConfiguration configuration)
{
var issuerSigningKey = configuration.GetIssuerSigningKey();
var data = Encoding.UTF8.GetBytes(issuerSigningKey);
var result = new SymmetricSecurityKey(data);
return result;
}
public static string[] GetCorsOrigins(this IConfiguration configuration)
{
string[] result =
configuration.GetValue<string>("App:CorsOrigins")
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.ToArray();
return result;
}
}
它为您节省了很多行,您只需编写干净且最少的代码:
...
x.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
IssuerSigningKey = _configuration.GetSymmetricSecurityKey(),
ValidAudience = _configuration.GetValidAudience(),
ValidIssuer = _configuration.GetValidIssuer()
};
也可以将 IConfiguration
实例注册为单例并在您需要的任何地方注入它 - 我使用 Autofac 容器,您可以这样做:
var appConfiguration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
builder.Register(c => appConfiguration).As<IConfigurationRoot>().SingleInstance();
你可以用 MS 依赖注入做同样的事情:
services.AddSingleton<IConfigurationRoot>(appConfiguration);
这是 ASP.NET Core 的完整用例!
articles.json
{
"shownArticlesCount": 3,
"articles": [
{
"title": "My Title 1",
"thumbnailLink": "example.com/img1.png",
"authorProfileLink": "example.com/@@alper",
"authorName": "Alper Ebicoglu",
"publishDate": "2018-04-17",
"text": "...",
"link": "..."
},
{
"title": "My Title 2",
"thumbnailLink": "example.com/img2.png",
"authorProfileLink": "example.com/@@alper",
"authorName": "Alper Ebicoglu",
"publishDate": "2018-04-17",
"text": "...",
"link": "..."
},
]
}
ArticleContainer.cs
public class ArticleContainer
{
public int ShownArticlesCount { get; set; }
public List<Article> Articles { get; set; }
}
public class Article
{
public string Title { get; set; }
public string ThumbnailLink { get; set; }
public string AuthorName { get; set; }
public string AuthorProfileLink { get; set; }
public DateTime PublishDate { get; set; }
public string Text { get; set; }
public string Link { get; set; }
}
Startup.cs
public class Startup
{
public IConfigurationRoot ArticleConfiguration { get; set; }
public Startup(IHostingEnvironment env)
{
ArticleConfiguration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("articles.json")
.Build();
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<ArticleContainer>(ArticleConfiguration);
}
}
Index.cshtml.cs
public class IndexModel : PageModel
{
public ArticleContainer ArticleContainer { get;set; }
private readonly IOptions<ArticleContainer> _articleContainer;
public IndexModel(IOptions<ArticleContainer> articleContainer)
{
_articleContainer = articleContainer;
}
public void OnGet()
{
ArticleContainer = _articleContainer.Value;
}
}
Index.cshtml.cs
<h1>@Model.ArticleContainer.ShownArticlesCount</h1>
使用 .NET Core 2.2,并以最简单的方式...
public IActionResult Index([FromServices] IConfiguration config)
{
var myValue = config.GetValue<string>("MyKey");
}
appsettings.json
通过构造函数或动作注入自动加载和可用,IConfiguration
上也有一个 GetSection
方法。如果您只需要 appsettings.json
.
,则无需更改 Startup.cs
或 Program.cs
通过调用Get<YourType>()
:
将其作为对象获取到控制器中
public IActionResult Index([FromServices] IConfiguration config)
{
BillModel model = config.GetSection("Yst.Requisites").Get<BillModel>();
return View(model);
}
您可以试试下面的代码。这对我有用。
public class Settings
{
private static IHttpContextAccessor _HttpContextAccessor;
public Settings(IHttpContextAccessor httpContextAccessor)
{
_HttpContextAccessor = httpContextAccessor;
}
public static void Configure(IHttpContextAccessor httpContextAccessor)
{
_HttpContextAccessor = httpContextAccessor;
}
public static IConfigurationBuilder Getbuilder()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
return builder;
}
public static string GetAppSetting(string key)
{
//return Convert.ToString(ConfigurationManager.AppSettings[key]);
var builder = Getbuilder();
var GetAppStringData = builder.Build().GetValue<string>("AppSettings:" + key);
return GetAppStringData;
}
public static string GetConnectionString(string key="DefaultName")
{
var builder = Getbuilder();
var ConnectionString = builder.Build().GetValue<string>("ConnectionStrings:"+key);
return ConnectionString;
}
}
我在这里创建了一个 class 来获取连接字符串和应用程序设置。
我Startup.cs文件你需要注册class如下。
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
Settings.Configure(httpContextAccessor);
}
}
.NET 核心 2.1.0
- 在根目录中创建 .json 文件
- 关于你的代码:
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var config = builder.Build();
3。安装以下依赖项:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.json
4.然后,重要:
右键单击 appsettings.json 文件 -> 单击属性 -> select 如果较新则复制:
最后,你可以这样做:
配置["key1"]
考虑到我的配置文件将如下所示:
{
"ConnectionStrings": "myconnection string here",
"key1": "value here"
}
.NET 核心 3.0
也许这不是从 appsettings.json 获取值的最佳方式,但它很简单并且在我的应用程序中有效!!
文件appsettings.json
{
"ConnectionStrings": {
"DefaultConnection":****;"
}
"AppSettings": {
"APP_Name": "MT_Service",
"APP_Version": "1.0.0"
}
}
控制器:
在上面:
using Microsoft.Extensions.Configuration;
在您的代码中:
var AppName = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("AppSettings")["APP_Name"];
首先你应该注入 IConfiguration 然后从 appsettings 中读取,你可以使用以下方法之一:
获取段数据
var redisConfig = configuration.GetSection("RedisConfig");
获取部分内的值
var redisServer = configuration.GetValue<string>("RedisConfig:ServerName");
获取节内的嵌套值
var redisExpireMInutes = configuration.GetValue<int>("RedisConfig:ServerName:ExpireMInutes");
.NET Core 2.2 方式
(毫无疑问,微软将在下一个 .NET 版本中将其再次更改为完全不同的内容。)
1。 appSettings.json
它可能看起来像这样。在这里我们将加载 Setting1 和 Setting2
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"Setting1": "abc",
"Setting2": 123
}
2。 AppSettings.cs
POCO class 保存 Setting1 和 Setting2。我们将把 appsettings.json 加载到这个 class 对象中。 POCO class 的结构应与 JSON 文件匹配,如果需要,属性可以嵌套在其他 properties/classes 中。
public class AppSettings
{
public string Setting1 { get; set; }
public int Setting2 { get; set; }
}
3 Startup.cs
将 appSettings.json 加载到您的 AppSettings 对象中并开始使用它:
public class Startup
{
public Startup(IConfiguration configuration)
{
AppSettings settings = new AppSettings();
Configuration = configuration;
configuration.Bind(settings);
// Now start using it
string setting1 = settings.Setting1;
int setting2 = settings.Setting2;
}
随着 netcoreapp 3.1 的最新迭代,您可以非常简单地完成此操作,而无需任何第三方依赖项。
我 created a gist for this,但是你可以使用这个 class 来读取 JSON 文件和 return 动态属性。
using System.Text.Json;
using System.IO;
class ConfigurationLoader
{
private dynamic configJsonData;
public ConfigurationLoader Load(string configFilePath = "appsettings.json")
{
var appSettings = File.ReadAllText(configFilePath);
this.configJsonData = JsonSerializer.Deserialize(appSettings, typeof(object));
return this;
}
public dynamic GetProperty(string key)
{
var properties = key.Split(".");
dynamic property = this.configJsonData;
foreach (var prop in properties)
{
property = property.GetProperty(prop);
}
return property;
}
}
我特意做了这个,这样我就可以在我的 dotnet 控制台应用程序中使用 appconfig.json。我只是把它放在我的 Program.Main
函数中:
var config = new ConfigurationLoader();
config.Load();
Console.WriteLine(config.GetProperty("Environment.Name"));
这将为 属性 return 一个 dynamic
对象。 (如果不是基元,则为 JsonElement)。
我的 appsettings.json
文件如下所示:
{
"Environment": {
"Token": "abc-123",
"Name": "Production"
}
}
对于 ASP.NET Core 3.1,您可以遵循以下文档:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1
当您创建新的 ASP.NET Core 3.1 项目或 .NET 5 项目时,您将在 Program.cs
中拥有以下配置行:
Host.CreateDefaultBuilder(args)
这会启用以下功能:
- ChainedConfigurationProvider : 添加现有的 IConfiguration 作为
资源。默认配置情况下,添加主机
配置并将其设置为应用程序的第一个来源
配置。
- appsettings.json 使用 JSON 配置
提供商。
- appsettings.Environment.json 使用 JSON 配置
提供商。例如,appsettings.Production.json 和
appsettings.Development.json.
- 应用运行时的应用机密
开发环境.
- 环境变量使用Environment
变量配置提供程序。
- 命令行参数使用
命令行配置提供程序。
这意味着您可以注入 IConfiguration
并使用字符串键获取值,甚至是嵌套值。喜欢IConfiguration ["Parent:Child"];
示例:
appsettings.json
{
"ApplicationInsights":
{
"Instrumentationkey":"putrealikeyhere"
}
}
WeatherForecast.cs
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
private readonly IConfiguration _configuration;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var key = _configuration["ApplicationInsights:InstrumentationKey"];
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
派对太晚了,但如果有人发现了。
您可以从 Microsoft.Extensions.Configuration;
调用 IConfiguration
public static IConfiguration Configuration { get; }
public static string MyAwesomeString = Configuration.GetSection("appSettings")["MyAwesomeString"].ToString();
这对我有用 .Net 5
我有一个 appsettings.development.json 文件。我选择了“开发”环境,这就是我在 development.json 文件中设置的原因。您可以在默认环境下使用 appsettings.josn。
使用此配置
创建了一个具有配置属性的 class
在 Startup 中注册了我的通话
我现在可以在我的控制器中访问
除了之外,还必须在构造函数中注入IConfiguration对象:
appsettings.js
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"AppSettings": {
"ServerUrl": "some url"
}
}
定义 AppSettings class
public class AppSettings
{
public string ServerUrl { get; set; }
}
Startup.cs
public class Startup
{
private readonly IConfiguration Configuration;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
}
}
控制器
[Route("api/[controller]")]
[ApiController]
public class AuthenticationController : ControllerBase
{
private readonly AppSettings config;
public AuthenticationController (IOptions<AppSettings> config)
{
this.config= config.Value;
}
[HttpGet("token")]
public ActionResult Token()
{
var server=config.ServerUrl;
}
适用于 .NET 5
对于ASP.NET Core 6.0你可以简单地:
appsetting.json
{
"AppSettings": {
"token": "1234"
}
}
TestModel.cs
using Microsoft.Extensions.Configuration
public class TestModel : PageModel
{
private readonly IConfiguration Configuration;
public TestModel(IConfiguration configuration)
{
Configuration = configuration;
}
public ContentResult OnGet()
{
var myToken = Configuration["AppSettings:Token"];
return Content($"myToken value: {myToken}");
}
}
我已经在文件 appsettings/Config 中设置了我的 AppSettings 数据。json 如下所示:
{
"AppSettings": {
"token": "1234"
}
}
我在网上搜索了如何从 .json 文件中读取 AppSettings 值,但没有得到任何有用的信息。
我试过:
var configuration = new Configuration();
var appSettings = configuration.Get("AppSettings"); // null
var token = configuration.Get("token"); // null
我知道 ASP.NET 4.0 可以做到这一点:
System.Configuration.ConfigurationManager.AppSettings["token"];
但是我如何在 ASP.NET Core 中执行此操作?
这有一些波折。我修改了这个答案,使其与 ASP.NET Core 2.0 保持同步(截至 2018 年 2 月 26 日)。
这主要取自the official documentation:
要在 ASP.NET 应用程序中使用设置,建议您仅在应用程序的 Startup
class 中实例化 Configuration
。然后,使用选项模式访问各个设置。假设我们有一个如下所示的 appsettings.json
文件:
{
"MyConfig": {
"ApplicationName": "MyApp",
"Version": "1.0.0"
}
}
我们有一个代表配置的 POCO 对象:
public class MyConfig
{
public string ApplicationName { get; set; }
public int Version { get; set; }
}
现在我们在Startup.cs
中构建配置:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
}
请注意,appsettings.json
将在 .NET Core 2.0 中默认注册。如果需要,我们还可以为每个环境注册一个 appsettings.{Environment}.json
配置文件。
如果我们想将我们的配置注入我们的控制器,我们需要在运行时注册它。我们这样做是通过 Startup.ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}
然后我们像这样注入它:
public class HomeController : Controller
{
private readonly IOptions<MyConfig> config;
public HomeController(IOptions<MyConfig> config)
{
this.config = config;
}
// GET: /<controller>/
public IActionResult Index() => View(config.Value);
}
全 Startup
class:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}
}
首先: Microsoft.Framework.ConfigurationModel 的程序集名称和命名空间已更改为 Microsoft.Framework.Configuration。所以你应该使用: 例如
"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"
作为 project.json
中的依赖项。如果您没有安装 7,请使用 beta5 或 6。
然后你可以在 Startup.cs
.
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddEnvironmentVariables();
Configuration = configurationBuilder.Build();
}
如果您随后想从 config.json 中检索一个变量,您可以使用以下命令立即获取它:
public void Configure(IApplicationBuilder app)
{
// Add .Value to get the token string
var token = Configuration.GetSection("AppSettings:token");
app.Run(async (context) =>
{
await context.Response.WriteAsync("This is a token with key (" + token.Key + ") " + token.Value);
});
}
或者您可以像这样创建一个名为 AppSettings 的 class:
public class AppSettings
{
public string token { get; set; }
}
并像这样配置服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
//mvc options
});
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
然后通过例如访问它像这样的控制器:
public class HomeController : Controller
{
private string _token;
public HomeController(IOptions<AppSettings> settings)
{
_token = settings.Options.token;
}
}
他们只是不断地改变东西——刚刚更新了 Visual Studio 并让整个项目炸弹,在恢复的道路上,新的方式看起来像这样:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
我一直漏掉这一行!
.SetBasePath(env.ContentRootPath)
如果你只是想获取代币的价值,那么使用
Configuration["AppSettings:token"]
对于 .NET Core 2.0,情况发生了一些变化。启动构造函数将 Configuration 对象作为参数,因此不需要使用 ConfigurationBuilder
。这是我的:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<StorageOptions>(Configuration.GetSection("AzureStorageConfig"));
}
我的POCO是上面提到的StorageOptions
对象:
namespace FictionalWebApp.Models
{
public class StorageOptions
{
public String StorageConnectionString { get; set; }
public String AccountName { get; set; }
public String AccountKey { get; set; }
public String DefaultEndpointsProtocol { get; set; }
public String EndpointSuffix { get; set; }
public StorageOptions() { }
}
}
配置实际上是我的 appsettings.json
文件的一个小节,名为 AzureStorageConfig
:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;",
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=fictionalwebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"AzureStorageConfig": {
"AccountName": "fictionalwebapp",
"AccountKey": "Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==",
"DefaultEndpointsProtocol": "https",
"EndpointSuffix": "core.windows.net",
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=fictionalwebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
}
}
我唯一要补充的是,由于构造函数已经更改,我没有测试是否需要做一些额外的事情来加载 appsettings.<environmentname>.json
而不是 appsettings.json
.
我怀疑这是个好习惯,但它在本地有效。如果我 publish/deploy(到 IIS Web 服务)失败,我会更新它。
第 1 步 - 将此程序集添加到 class 的顶部(在我的例子中,控制器 class):
using Microsoft.Extensions.Configuration;
第 2 步 - 添加此内容或类似内容:
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
第 3 步 - 通过执行此操作调用密钥的值(returns 字符串):
config["NameOfYourKey"]
只是为了补充 Yuval Itzchakov 的回答。
你可以加载没有构建器功能的配置,你可以直接注入它。
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
对于 .NET Core 2.0,您可以简单地:
在 appsettings.json 中声明你的 key/value 对:
{
"MyKey": "MyValue"
}
在startup.cs注入配置服务,使用服务获取值
using Microsoft.Extensions.Configuration;
public class Startup
{
public void Configure(IConfiguration configuration,
... other injected services
)
{
app.Run(async (context) =>
{
string myValue = configuration["MyKey"];
await context.Response.WriteAsync(myValue);
});
这是"cheating"吗?我刚刚在 Startup class 中将我的配置设为静态,然后我可以从其他任何地方访问它:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public static IConfiguration Configuration { get; set; }
以下适用于控制台应用程序;
安装以下 NuGet 包 (
.csproj
);<ItemGroup> <PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0-preview2-35157" /> <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0-preview2-35157" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0-preview2-35157" /> </ItemGroup>
在根级别创建
appsettings.json
。右键单击它并 "Copy to Output Directory" as "Copy if newer".示例配置文件:
{ "AppConfig": { "FilePath": "C:\temp\logs\output.txt" } }
Program.cs
configurationSection.Key
和configurationSection.Value
将具有配置属性。static void Main(string[] args) { try { IConfigurationBuilder builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); IConfigurationRoot configuration = builder.Build(); // configurationSection.Key => FilePath // configurationSection.Value => C:\temp\logs\output.txt IConfigurationSection configurationSection = configuration.GetSection("AppConfig").GetSection("FilePath"); } catch (Exception e) { Console.WriteLine(e); } }
除了现有的答案之外,我想提一下,为了简单起见,有时 扩展方法 对于 IConfiguration
可能很有用。
我在 appsettings.json 中保留了 JWT 配置,因此我的扩展方法 class 如下所示:
public static class ConfigurationExtensions
{
public static string GetIssuerSigningKey(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:SecurityKey");
return result;
}
public static string GetValidIssuer(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:Issuer");
return result;
}
public static string GetValidAudience(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:Audience");
return result;
}
public static string GetDefaultPolicy(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Policies:Default");
return result;
}
public static SymmetricSecurityKey GetSymmetricSecurityKey(this IConfiguration configuration)
{
var issuerSigningKey = configuration.GetIssuerSigningKey();
var data = Encoding.UTF8.GetBytes(issuerSigningKey);
var result = new SymmetricSecurityKey(data);
return result;
}
public static string[] GetCorsOrigins(this IConfiguration configuration)
{
string[] result =
configuration.GetValue<string>("App:CorsOrigins")
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.ToArray();
return result;
}
}
它为您节省了很多行,您只需编写干净且最少的代码:
...
x.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
IssuerSigningKey = _configuration.GetSymmetricSecurityKey(),
ValidAudience = _configuration.GetValidAudience(),
ValidIssuer = _configuration.GetValidIssuer()
};
也可以将 IConfiguration
实例注册为单例并在您需要的任何地方注入它 - 我使用 Autofac 容器,您可以这样做:
var appConfiguration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
builder.Register(c => appConfiguration).As<IConfigurationRoot>().SingleInstance();
你可以用 MS 依赖注入做同样的事情:
services.AddSingleton<IConfigurationRoot>(appConfiguration);
这是 ASP.NET Core 的完整用例!
articles.json
{
"shownArticlesCount": 3,
"articles": [
{
"title": "My Title 1",
"thumbnailLink": "example.com/img1.png",
"authorProfileLink": "example.com/@@alper",
"authorName": "Alper Ebicoglu",
"publishDate": "2018-04-17",
"text": "...",
"link": "..."
},
{
"title": "My Title 2",
"thumbnailLink": "example.com/img2.png",
"authorProfileLink": "example.com/@@alper",
"authorName": "Alper Ebicoglu",
"publishDate": "2018-04-17",
"text": "...",
"link": "..."
},
]
}
ArticleContainer.cs
public class ArticleContainer
{
public int ShownArticlesCount { get; set; }
public List<Article> Articles { get; set; }
}
public class Article
{
public string Title { get; set; }
public string ThumbnailLink { get; set; }
public string AuthorName { get; set; }
public string AuthorProfileLink { get; set; }
public DateTime PublishDate { get; set; }
public string Text { get; set; }
public string Link { get; set; }
}
Startup.cs
public class Startup
{
public IConfigurationRoot ArticleConfiguration { get; set; }
public Startup(IHostingEnvironment env)
{
ArticleConfiguration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("articles.json")
.Build();
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<ArticleContainer>(ArticleConfiguration);
}
}
Index.cshtml.cs
public class IndexModel : PageModel
{
public ArticleContainer ArticleContainer { get;set; }
private readonly IOptions<ArticleContainer> _articleContainer;
public IndexModel(IOptions<ArticleContainer> articleContainer)
{
_articleContainer = articleContainer;
}
public void OnGet()
{
ArticleContainer = _articleContainer.Value;
}
}
Index.cshtml.cs
<h1>@Model.ArticleContainer.ShownArticlesCount</h1>
使用 .NET Core 2.2,并以最简单的方式...
public IActionResult Index([FromServices] IConfiguration config)
{
var myValue = config.GetValue<string>("MyKey");
}
appsettings.json
通过构造函数或动作注入自动加载和可用,IConfiguration
上也有一个 GetSection
方法。如果您只需要 appsettings.json
.
Startup.cs
或 Program.cs
通过调用Get<YourType>()
:
public IActionResult Index([FromServices] IConfiguration config)
{
BillModel model = config.GetSection("Yst.Requisites").Get<BillModel>();
return View(model);
}
您可以试试下面的代码。这对我有用。
public class Settings
{
private static IHttpContextAccessor _HttpContextAccessor;
public Settings(IHttpContextAccessor httpContextAccessor)
{
_HttpContextAccessor = httpContextAccessor;
}
public static void Configure(IHttpContextAccessor httpContextAccessor)
{
_HttpContextAccessor = httpContextAccessor;
}
public static IConfigurationBuilder Getbuilder()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
return builder;
}
public static string GetAppSetting(string key)
{
//return Convert.ToString(ConfigurationManager.AppSettings[key]);
var builder = Getbuilder();
var GetAppStringData = builder.Build().GetValue<string>("AppSettings:" + key);
return GetAppStringData;
}
public static string GetConnectionString(string key="DefaultName")
{
var builder = Getbuilder();
var ConnectionString = builder.Build().GetValue<string>("ConnectionStrings:"+key);
return ConnectionString;
}
}
我在这里创建了一个 class 来获取连接字符串和应用程序设置。
我Startup.cs文件你需要注册class如下。
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
Settings.Configure(httpContextAccessor);
}
}
.NET 核心 2.1.0
- 在根目录中创建 .json 文件
- 关于你的代码:
var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var config = builder.Build();
3。安装以下依赖项:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.json
4.然后,重要:
右键单击 appsettings.json 文件 -> 单击属性 -> select 如果较新则复制:
最后,你可以这样做:
配置["key1"]
考虑到我的配置文件将如下所示:
{ "ConnectionStrings": "myconnection string here", "key1": "value here" }
.NET 核心 3.0
也许这不是从 appsettings.json 获取值的最佳方式,但它很简单并且在我的应用程序中有效!!
文件appsettings.json
{
"ConnectionStrings": {
"DefaultConnection":****;"
}
"AppSettings": {
"APP_Name": "MT_Service",
"APP_Version": "1.0.0"
}
}
控制器:
在上面:
using Microsoft.Extensions.Configuration;
在您的代码中:
var AppName = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("AppSettings")["APP_Name"];
首先你应该注入 IConfiguration 然后从 appsettings 中读取,你可以使用以下方法之一:
获取段数据
var redisConfig = configuration.GetSection("RedisConfig");
获取部分内的值
var redisServer = configuration.GetValue<string>("RedisConfig:ServerName");
获取节内的嵌套值
var redisExpireMInutes = configuration.GetValue<int>("RedisConfig:ServerName:ExpireMInutes");
.NET Core 2.2 方式
(毫无疑问,微软将在下一个 .NET 版本中将其再次更改为完全不同的内容。)
1。 appSettings.json
它可能看起来像这样。在这里我们将加载 Setting1 和 Setting2
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"Setting1": "abc",
"Setting2": 123
}
2。 AppSettings.cs
POCO class 保存 Setting1 和 Setting2。我们将把 appsettings.json 加载到这个 class 对象中。 POCO class 的结构应与 JSON 文件匹配,如果需要,属性可以嵌套在其他 properties/classes 中。
public class AppSettings
{
public string Setting1 { get; set; }
public int Setting2 { get; set; }
}
3 Startup.cs
将 appSettings.json 加载到您的 AppSettings 对象中并开始使用它:
public class Startup
{
public Startup(IConfiguration configuration)
{
AppSettings settings = new AppSettings();
Configuration = configuration;
configuration.Bind(settings);
// Now start using it
string setting1 = settings.Setting1;
int setting2 = settings.Setting2;
}
随着 netcoreapp 3.1 的最新迭代,您可以非常简单地完成此操作,而无需任何第三方依赖项。
我 created a gist for this,但是你可以使用这个 class 来读取 JSON 文件和 return 动态属性。
using System.Text.Json;
using System.IO;
class ConfigurationLoader
{
private dynamic configJsonData;
public ConfigurationLoader Load(string configFilePath = "appsettings.json")
{
var appSettings = File.ReadAllText(configFilePath);
this.configJsonData = JsonSerializer.Deserialize(appSettings, typeof(object));
return this;
}
public dynamic GetProperty(string key)
{
var properties = key.Split(".");
dynamic property = this.configJsonData;
foreach (var prop in properties)
{
property = property.GetProperty(prop);
}
return property;
}
}
我特意做了这个,这样我就可以在我的 dotnet 控制台应用程序中使用 appconfig.json。我只是把它放在我的 Program.Main
函数中:
var config = new ConfigurationLoader();
config.Load();
Console.WriteLine(config.GetProperty("Environment.Name"));
这将为 属性 return 一个 dynamic
对象。 (如果不是基元,则为 JsonElement)。
我的 appsettings.json
文件如下所示:
{
"Environment": {
"Token": "abc-123",
"Name": "Production"
}
}
对于 ASP.NET Core 3.1,您可以遵循以下文档:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1
当您创建新的 ASP.NET Core 3.1 项目或 .NET 5 项目时,您将在 Program.cs
中拥有以下配置行:
Host.CreateDefaultBuilder(args)
这会启用以下功能:
- ChainedConfigurationProvider : 添加现有的 IConfiguration 作为 资源。默认配置情况下,添加主机 配置并将其设置为应用程序的第一个来源 配置。
- appsettings.json 使用 JSON 配置 提供商。
- appsettings.Environment.json 使用 JSON 配置 提供商。例如,appsettings.Production.json 和 appsettings.Development.json.
- 应用运行时的应用机密 开发环境.
- 环境变量使用Environment 变量配置提供程序。
- 命令行参数使用 命令行配置提供程序。
这意味着您可以注入 IConfiguration
并使用字符串键获取值,甚至是嵌套值。喜欢IConfiguration ["Parent:Child"];
示例:
appsettings.json
{
"ApplicationInsights":
{
"Instrumentationkey":"putrealikeyhere"
}
}
WeatherForecast.cs
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
private readonly IConfiguration _configuration;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var key = _configuration["ApplicationInsights:InstrumentationKey"];
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
派对太晚了,但如果有人发现了。
您可以从 Microsoft.Extensions.Configuration;
调用 IConfigurationpublic static IConfiguration Configuration { get; }
public static string MyAwesomeString = Configuration.GetSection("appSettings")["MyAwesomeString"].ToString();
这对我有用 .Net 5
我有一个 appsettings.development.json 文件。我选择了“开发”环境,这就是我在 development.json 文件中设置的原因。您可以在默认环境下使用 appsettings.josn。
使用此配置
创建了一个具有配置属性的 class
在 Startup 中注册了我的通话
我现在可以在我的控制器中访问
除了
appsettings.js
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"AppSettings": {
"ServerUrl": "some url"
}
}
定义 AppSettings class
public class AppSettings
{
public string ServerUrl { get; set; }
}
Startup.cs
public class Startup
{
private readonly IConfiguration Configuration;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
}
}
控制器
[Route("api/[controller]")]
[ApiController]
public class AuthenticationController : ControllerBase
{
private readonly AppSettings config;
public AuthenticationController (IOptions<AppSettings> config)
{
this.config= config.Value;
}
[HttpGet("token")]
public ActionResult Token()
{
var server=config.ServerUrl;
}
适用于 .NET 5
对于ASP.NET Core 6.0你可以简单地:
appsetting.json
{
"AppSettings": {
"token": "1234"
}
}
TestModel.cs
using Microsoft.Extensions.Configuration
public class TestModel : PageModel
{
private readonly IConfiguration Configuration;
public TestModel(IConfiguration configuration)
{
Configuration = configuration;
}
public ContentResult OnGet()
{
var myToken = Configuration["AppSettings:Token"];
return Content($"myToken value: {myToken}");
}
}