如何从.json文件中读取AppSettings值。网络核心

我在文件AppSettings /Config .json中设置了我的AppSettings数据,如下所示:

{
"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中做到这一点呢?网络核心?

695364 次浏览

这其中有一些曲折。我已经将这个答案修改为最新的ASP。NET Core 2.0(截至2018年2月26日)。

这主要来自官方文件:

使用ASP. exe中的设置。NET应用程序中,建议只在应用程序的Startup类中实例化Configuration。然后,使用Options模式访问各个设置。假设我们有一个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();
}
}

注意。net Core 2.0中的appsettings.json将是默认注册。如果需要,我们也可以为每个环境注册一个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类:

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"));
}
}
< p >首先: Microsoft.Framework.ConfigurationModel的程序集名称和命名空间已更改为Microsoft.Framework.Configuration。所以你应该使用: 例如< / p >
"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"

作为project.json中的依赖项。如果你没有安装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();
}

如果您想从配置中检索一个变量。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的类:

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

我怀疑这是一个好的做法,但它在当地是有效的。如果在发布/部署(到IIS web服务)时失败,我将更新它。

步骤1 -将这个程序集添加到类的顶部(在我的例子中,控制器类):

using Microsoft.Extensions.Configuration;

步骤2 -添加这个或类似的东西:

var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();

步骤3 -通过这样做调用你的键的值(返回字符串):

config["NameOfYourKey"]

只是为了补充Yuval Itzchakov的回答。

你可以在没有生成器函数的情况下加载配置,你可以直接注入它。

public IConfiguration Configuration { get; set; }


public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

对于。net Core 2.0,你可以简单地:

在appsettings.json中声明你的键值对:

{
"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);
});

这是“作弊”吗?我只是把我的配置在启动类静态,然后我可以从其他任何地方访问它:

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; }

以下工作用于控制台应用程序;

  1. 安装以下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>
    
  2. Create appsettings.json at root level. Right click on it and "Copy to Output Directory" as "Copy if newer".

  3. Sample configuration file:

    {
    "AppConfig": {
    "FilePath": "C:\\temp\\logs\\output.txt"
    }
    }
    
  4. Program.cs

    configurationSection.Key and configurationSection.Value will have config properties.

    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使用扩展方法可能是有用的。

我把JWT配置保存在appsettings中。Json,所以我的扩展方法类看起来如下:

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的完整用例。网的核心!

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.csProgram.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;
}
}

在这里,我创建了一个类来获取连接字符串和应用程序设置。

我Startup.cs文件你需要注册类如下。

public class Startup
{


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
Settings.Configure(httpContextAccessor);
}
}

.NET Core 2.1.0

  1. 在根目录上创建.json文件
  2. 在你的代码中:
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。>单击属性->选择复制如果更新: enter image description here < / p >

  1. 最后,你可以这样做:

    配置(“key1”)< / p >

考虑到我的配置文件将是这样的:

{
"ConnectionStrings": "myconnection string here",
"key1": "value here"
}

.NET Core 3.0 / .NET

这是一个时髦而简单的解决方案。

文件appsettings.json

{
"ConnectionStrings": {
"DefaultConnection": "****;"
},
"AppSettings": {
"APP_Name": "MY_Service",
"SampleIntValue": 100
}
}

控制器:

在上面:

using Microsoft.Extensions.Configuration;

在你的代码中:

VAR 1:

var AppName = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("AppSettings")["APP_Name"];

< >强VAR 2: (用于读取多个值或数字)

var MyConfig = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var IntExample = MyConfig.GetValue<int>("AppSettings:SampleIntValue");
var AppName = MyConfig.GetValue<string>("AppSettings:APP_Name");

首先你应该注入IConfiguration,然后从appsettings读取,你可以使用以下方法之一:

  1. 获取section数据

    var redisConfig = configuration.GetSection("RedisConfig");
    
  2. Get a value within a section

    var redisServer = configuration.GetValue<string>("RedisConfig:ServerName");
    
  3. Get nested value within section

    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

类保存Setting1和Setting2。我们将加载应用程序设置。Json到这个类对象中。POCO类的结构应该与JSON文件匹配,如果需要,属性可以嵌套在其他属性/类中。

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的最新版本的发布,您可以非常简单地做到这一点,不需要任何第三方依赖。

为这篇文章创造了一个主旨,但你可以使用这个类读取JSON文件并返回动态属性。

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;
}
}

我特意做了这个,这样我就可以使用appconfig。Json在我的dotnet控制台应用程序。我刚刚把这个放在Program.Main函数中:

var config = new ConfigurationLoader();
config.Load();
Console.WriteLine(config.GetProperty("Environment.Name"));
这将返回属性的dynamic对象。(如果不是原语,则为JsonElement)。 我的appsettings.json文件看起来像这样:

{
"Environment": {
"Token": "abc-123",
"Name": "Production"
}
}

ASP。NET Core 3.1可以遵循以下文档:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1

当您创建一个新的ASP。NET Core 3.1项目或。NET 5项目,你将在Program.cs中有以下配置行:

Host.CreateDefaultBuilder(args)

这将启用以下功能:

  1. ChainedConfigurationProvider:添加一个现有的IConfiguration 源。默认情况下,添加主机 配置并将其设置为应用程序的第一个源 李配置。< / > <李> appsettings。使用json配置 李提供者。< / > <李> appsettings.Environment。使用json配置 提供者。例如,appsettings.Production.json和 李appsettings.Development.json。< / >
  2. 当应用程序运行在 李开发环境。< / >
  3. 环境变量 变量配置提供程序
  4. 使用 命令行配置提供程序

这意味着你可以注入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/6

我有一个appsettings.development.json文件。我有“发展”;环境选择,这就是为什么我有设置在我的开发。json文件。你可以使用appsettings。使用默认环境的Josn。

enter image description here

这样的配置

enter image description here

创建一个具有配置属性的类

enter image description here

在Startup中注册我的呼叫

enter image description here

我现在可以访问我的控制器

enter image description here

除了阿里的回答,你还必须在构造函数中注入IConfiguration对象:

appsettings.js

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"AppSettings": {
"ServerUrl": "some url"
}
  

}

定义AppSettings类

    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}");
}
}