我试图在我的ASP.NET核心WebAPI中访问AppSettings作为服务 . 当我执行Configuration.GetSection(“AppSettings”)时,我得到null,但我可以访问配置值为Configuration [“AppSettings:StorageConnectionKey:AccountName”] . 我不确定我做错了什么 .
我的Startup.cs如下所示
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Library;
namespace Athraya
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
// .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddOptions();
services.Configure<AppSettings>(options => Configuration.GetSection("AppSettings"));
// *If* you need access to generic IConfiguration this is **required**
services.AddSingleton<IConfiguration>(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
}
}
}
我的appsetting是
{
"AppSettings": {
"StorageConnectionKey": {
"AccountName": "myaccountName",
"AccountKey": "abc"
},
"CloudContainerkey": {
"ContainerName": "mycontainername",
"FileName": "db.dat"
}
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
我有一个图书馆项目,我有所需的课程
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library
{
public class AppSettings
{
public StorageConnectionKey storageKey {get; set; }
public CloudContainerKey containerKey { get; set; }
}
}
namespace Library
{
public class CloudContainerKey
{
public string ContainerName { get; set; }
public string FileName { get; set; }
}
}
namespace Library
{
public class StorageConnectionKey
{
public string AccountName { get; set; }
public string AccountKey { get; set; }
}
}
我试图把它作为控制器
public class ValuesController : Controller
{
private readonly AppSettings _appSettings;
public ValuesController(IOptions<AppSettings> settings)
{
_appSettings = settings.Value;
}
}
任何帮助在这里表示赞赏 .
2 回答
要使用IConfiguration实例设置AppSettings,请使用:
此外,您需要使用相同的属性名称作为设置参数 . 将
AppSettings
修改为:在您的情况下,在使用扩展方法时,您具有null,允许手动注册用于配置选项的操作 . 如果查看方法定义,您将看到:
换句话说,当您使用follow代码时,您注册lambda函数并已使用
AppSettings
的实例:我想它应该是这样的: