gpt4 book ai didi

c# - 访问 ASP.NET Core 中的配置选项 : options pattern

转载 作者:行者123 更新时间:2023-11-30 20:17:19 25 4
gpt4 key购买 nike

我有一个 ASP.NET Core 应用程序。我尝试使用选项模式,但它似乎不起作用。

我有以下 appsettings.json:

{
"ConnectionStrings": {
"MyTablesConnectionString": "Default[...];EndpointSuffix=core.windows.net"
},

"Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }
}

下面的 ConnectionStrings

public class ConnectionStrings {
public ConnectionStrings() {
MyTablesConnectionString = "default value";
}

public string MyTablesConnectionString { get; set; }
}

这是我的Startup.cs

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, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();

// HERE IS THE GOOD VALUE !!!!!!!!
Debug.WriteLine($"Connection string is:{Configuration["ConnectionStrings:MyTablesConnectionString"]}");
}

public void ConfigureServices(IServiceCollection services)
{
// Adds services required for using options.
services.AddOptions();
// Register the IConfiguration instance which "ConnectionStrings" binds against.
services.Configure<ConnectionStrings>(Configuration);

// Add framework services.
services.AddMvc();
}

但是,在带有以下 Controller 的开发机器上使用它时

private readonly ConnectionStrings azureConnectionString;
public HelloWorldController(IOptions<ConnectionStrings> optionsAccessor)
{
// HERE IS THE "DEFAULT" VALUE ?!!!!!!!!
azureConnectionString = optionsAccessor.Value;
}

我看到使用的是“默认值”而不是 json 文件中的值(无效的)。我错过了什么吗?

最佳答案

您需要像这样绑定(bind) ConnectionStrings 部分:

services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));

目前它期望从您的类中找到属性“ConnectionStrings”或“Logging”,因为您正在绑定(bind)根。

关于c# - 访问 ASP.NET Core 中的配置选项 : options pattern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45058329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com