将配置作为服务asp.net核心访问

时间:2017-03-13 18:15:23

标签: c# asp.net asp.net-core .net-core asp.net-core-webapi

我正在尝试在我的ASP.NET核心WebAPI中访问AppSettings作为服务。当我执行Configuration.GetSection(" AppSettings")时,我得到null但我可以访问配置值作为配置[" 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;
        }
}

欢迎任何帮助。

3 个答案:

答案 0 :(得分:1)

要使用IConfiguration实例设置AppSettings,请使用:

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

此外,您需要使用相同的属性名称作为设置参数。将您的AppSettings修改为:

public class AppSettings
{
    public StorageConnectionKey StorageConnectionKey {get; set; }
    public CloudContainerKey CloudContainerKey { get; set; }
}

在您的情况下,在使用扩展方法时,您具有null,允许手动注册用于配置选项的操作。如果查看方法定义,您将看到:

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

换句话说,当您使用follow代码时,您注册lambda函数并已使用AppSettings的实例:

services.Configure<AppSettings>(option =>
{
    // option here is the AppSettings and so we can override value like:
    option.StorageConnectionKey = "some_new_value";
});

答案 1 :(得分:0)

我认为应该是这样的:

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

答案 2 :(得分:0)

假设您具有以下设置

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

您可以阅读我的完整博客文章A Step by Step Guide for ASP.NET Core Configuration,其中详细介绍了所有这些步骤。