访问配置作为服务 asp.net 核心
Accessing Configuration as service asp.net core
我正尝试在我的 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();
}
}
}
我的应用设置是
{
"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;
}
}
感谢任何帮助。
我觉得应该是这样的:
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
要使用 IConfiguration 实例设置 AppSettings,请使用:
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
此外,您需要使用与设置参数相同的 属性 名称。将您的 AppSettings
修改为:
public class AppSettings
{
public StorageConnectionKey StorageConnectionKey {get; set; }
public CloudContainerKey CloudContainerKey { get; set; }
}
在你的例子中,你有空,因为你使用扩展方法,允许注册一个用于手动配置选项的操作。如果你查看方法定义,你会看到:
//
// Summary:
// Registers an action used to configure a particular type of options. ///
//
// Parameters:
// services:
// The Microsoft.Extensions.DependencyInjection.IServiceCollection to add the services
// to.
//
// configureOptions:
// The action used to configure the options.
//
// Type parameters:
// TOptions:
// The options type to be configured.
//
// Returns:
// The Microsoft.Extensions.DependencyInjection.IServiceCollection so that additional
// calls can be chained.
public static IServiceCollection Configure<TOptions>(this IServiceCollection services,
Action<TOptions> configureOptions) where TOptions : class;
换句话说,当您使用以下代码时,您注册了 lambda 函数并且已经使用了 AppSettings
:
的实例
services.Configure<AppSettings>(option =>
{
// option here is the AppSettings and so we can override value like:
option.StorageConnectionKey = "some_new_value";
});
假设您有以下设置
"MyApplication": {
"Name": "Demo Configuration Application (Development)",
"Version": "1.1",
"DefaultUrl": "http://localhost:3030",
"Support": {
"Email": "support@demoapp.com",
"Phone": "123456789"
}
}
首先您需要创建相应的 C# 类,其中 属性 名称应与上述 JSON 设置匹配。
public class ApplicationOptions
{
public const string MyApplication = "MyApplication";
public string Name { get; set; }
public decimal Version { get; set; }
public string DefaultUrl { get; set; }
public SupportOptions Support { get; set; }
}
public class SupportOptions
{
public const string Support = "Support";
public string Email { get; set; }
public string Phone { get; set; }
}
接下来您需要在 Startup.cs 文件中绑定您的配置设置,如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<ApplicationOptions>(Configuration.GetSection(ApplicationOptions.MyApplication));
...
}
接下来您可以使用选项模式在控制器或服务中注入配置
private readonly ApplicationOptions _options;
public HomeController(IOptions<ApplicationOptions> options)
{
_options = options.Value;
}
最后可以读取设置如下:
public IActionResult Index()
{
ViewBag.ApplicationName = _options.Name;
ViewBag.ApplicationVersion = _options.Version;
ViewBag.ApplicationUrl = _options.DefaultUrl;
ViewBag.SupportEmail = _options.Support.Email;
ViewBag.SupportPhone = _options.Support.Phone;
return View();
}
您可以阅读我的完整博客 post A Step by Step Guide for ASP.NET Core Configuration 更详细地解释所有这些步骤。
我正尝试在我的 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();
}
}
}
我的应用设置是
{
"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;
}
}
感谢任何帮助。
我觉得应该是这样的:
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
要使用 IConfiguration 实例设置 AppSettings,请使用:
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
此外,您需要使用与设置参数相同的 属性 名称。将您的 AppSettings
修改为:
public class AppSettings
{
public StorageConnectionKey StorageConnectionKey {get; set; }
public CloudContainerKey CloudContainerKey { get; set; }
}
在你的例子中,你有空,因为你使用扩展方法,允许注册一个用于手动配置选项的操作。如果你查看方法定义,你会看到:
//
// Summary:
// Registers an action used to configure a particular type of options. ///
//
// Parameters:
// services:
// The Microsoft.Extensions.DependencyInjection.IServiceCollection to add the services
// to.
//
// configureOptions:
// The action used to configure the options.
//
// Type parameters:
// TOptions:
// The options type to be configured.
//
// Returns:
// The Microsoft.Extensions.DependencyInjection.IServiceCollection so that additional
// calls can be chained.
public static IServiceCollection Configure<TOptions>(this IServiceCollection services,
Action<TOptions> configureOptions) where TOptions : class;
换句话说,当您使用以下代码时,您注册了 lambda 函数并且已经使用了 AppSettings
:
services.Configure<AppSettings>(option =>
{
// option here is the AppSettings and so we can override value like:
option.StorageConnectionKey = "some_new_value";
});
假设您有以下设置
"MyApplication": {
"Name": "Demo Configuration Application (Development)",
"Version": "1.1",
"DefaultUrl": "http://localhost:3030",
"Support": {
"Email": "support@demoapp.com",
"Phone": "123456789"
}
}
首先您需要创建相应的 C# 类,其中 属性 名称应与上述 JSON 设置匹配。
public class ApplicationOptions
{
public const string MyApplication = "MyApplication";
public string Name { get; set; }
public decimal Version { get; set; }
public string DefaultUrl { get; set; }
public SupportOptions Support { get; set; }
}
public class SupportOptions
{
public const string Support = "Support";
public string Email { get; set; }
public string Phone { get; set; }
}
接下来您需要在 Startup.cs 文件中绑定您的配置设置,如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<ApplicationOptions>(Configuration.GetSection(ApplicationOptions.MyApplication));
...
}
接下来您可以使用选项模式在控制器或服务中注入配置
private readonly ApplicationOptions _options;
public HomeController(IOptions<ApplicationOptions> options)
{
_options = options.Value;
}
最后可以读取设置如下:
public IActionResult Index()
{
ViewBag.ApplicationName = _options.Name;
ViewBag.ApplicationVersion = _options.Version;
ViewBag.ApplicationUrl = _options.DefaultUrl;
ViewBag.SupportEmail = _options.Support.Email;
ViewBag.SupportPhone = _options.Support.Phone;
return View();
}
您可以阅读我的完整博客 post A Step by Step Guide for ASP.NET Core Configuration 更详细地解释所有这些步骤。