作为服务ASP.NET核心访问配置



我正在尝试将AppSettings作为我的ASP.NET Core WebAPI中的服务访问。当我进行配置时。getSection(" appSettings"),我会得到null,但可以访问配置值作为配置[" appsettings:storageconnectionkey:councorname"]。我不确定我在做什么错。

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

这里的任何帮助将不胜感激。

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

我认为应该这样:

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

假设您有以下设置

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

您可以阅读我的完整博客文章ASP.NET核心配置的逐步指南,以详细说明所有这些步骤。

最新更新