<bdo id='9TkSO'></bdo><ul id='9TkSO'></ul>
      <legend id='9TkSO'><style id='9TkSO'><dir id='9TkSO'><q id='9TkSO'></q></dir></style></legend>
    1. <i id='9TkSO'><tr id='9TkSO'><dt id='9TkSO'><q id='9TkSO'><span id='9TkSO'><b id='9TkSO'><form id='9TkSO'><ins id='9TkSO'></ins><ul id='9TkSO'></ul><sub id='9TkSO'></sub></form><legend id='9TkSO'></legend><bdo id='9TkSO'><pre id='9TkSO'><center id='9TkSO'></center></pre></bdo></b><th id='9TkSO'></th></span></q></dt></tr></i><div id='9TkSO'><tfoot id='9TkSO'></tfoot><dl id='9TkSO'><fieldset id='9TkSO'></fieldset></dl></div>
    2. <small id='9TkSO'></small><noframes id='9TkSO'>

      1. <tfoot id='9TkSO'></tfoot>
      2. 从 .net 核心中的 appsettings.json 获取价值

        Getting value from appsettings.json in .net core(从 .net 核心中的 appsettings.json 获取价值)

      3. <legend id='nu8z3'><style id='nu8z3'><dir id='nu8z3'><q id='nu8z3'></q></dir></style></legend>
          <tbody id='nu8z3'></tbody>
              <tfoot id='nu8z3'></tfoot>
              <i id='nu8z3'><tr id='nu8z3'><dt id='nu8z3'><q id='nu8z3'><span id='nu8z3'><b id='nu8z3'><form id='nu8z3'><ins id='nu8z3'></ins><ul id='nu8z3'></ul><sub id='nu8z3'></sub></form><legend id='nu8z3'></legend><bdo id='nu8z3'><pre id='nu8z3'><center id='nu8z3'></center></pre></bdo></b><th id='nu8z3'></th></span></q></dt></tr></i><div id='nu8z3'><tfoot id='nu8z3'></tfoot><dl id='nu8z3'><fieldset id='nu8z3'></fieldset></dl></div>

              1. <small id='nu8z3'></small><noframes id='nu8z3'>

                  <bdo id='nu8z3'></bdo><ul id='nu8z3'></ul>

                  本文介绍了从 .net 核心中的 appsettings.json 获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  不确定我在这里遗漏了什么,但我无法从我的 .net 核心应用程序中的 appsettings.json 获取值.我的 appsettings.json 为:

                  Not sure what am I missing here but I am not able to get the values from my appsettings.json in my .net core application. I have my appsettings.json as:

                  {
                      "AppSettings": {
                          "Version": "One"
                      }
                  }
                  

                  启动:

                  public class Startup
                  {
                      private IConfigurationRoot _configuration;
                      public Startup(IHostingEnvironment env)
                      {
                          _configuration = new ConfigurationBuilder()
                      }
                      public void ConfigureServices(IServiceCollection services)
                      {
                        //Here I setup to read appsettings        
                        services.Configure<AppSettings>(_configuration.GetSection("AppSettings"));
                      }
                  }
                  

                  型号:

                  public class AppSettings
                  {
                      public string Version{ get; set; }
                  }
                  

                  控制器:

                  public class HomeController : Controller
                  {
                      private readonly AppSettings _mySettings;
                  
                      public HomeController(IOptions<AppSettings> settings)
                      {
                          //This is always null
                          _mySettings = settings.Value;
                      }
                  }
                  

                  _mySettings 始终为空.我在这里有什么遗漏吗?

                  _mySettings is always null. Is there something that I am missing here?

                  推荐答案

                  程序和启动类

                  .NET Core 2.x

                  您不需要在 Startup 构造函数中新建 IConfiguration.它的实现将由 DI 系统注入.

                  Program and Startup class

                  .NET Core 2.x

                  You don't need to new IConfiguration in the Startup constructor. Its implementation will be injected by the DI system.

                  // Program.cs
                  public class Program
                  {
                      public static void Main(string[] args)
                      {
                          BuildWebHost(args).Run();
                      }
                  
                      public static IWebHost BuildWebHost(string[] args) =>
                          WebHost.CreateDefaultBuilder(args)
                              .UseStartup<Startup>()
                              .Build();            
                  }
                  
                  // Startup.cs
                  public class Startup
                  {
                      public IHostingEnvironment HostingEnvironment { get; private set; }
                      public IConfiguration Configuration { get; private set; }
                  
                      public Startup(IConfiguration configuration, IHostingEnvironment env)
                      {
                          this.HostingEnvironment = env;
                          this.Configuration = configuration;
                      }
                  }
                  

                  .NET Core 1.x

                  您需要告诉 Startup 加载 appsettings 文件.

                  .NET Core 1.x

                  You need to tell Startup to load the appsettings files.

                  // Program.cs
                  public class Program
                  {
                      public static void Main(string[] args)
                      {
                          var host = new WebHostBuilder()
                              .UseKestrel()
                              .UseContentRoot(Directory.GetCurrentDirectory())
                              .UseIISIntegration()
                              .UseStartup<Startup>()
                              .UseApplicationInsights()
                              .Build();
                  
                          host.Run();
                      }
                  }
                  
                  //Startup.cs
                  public class Startup
                  {
                      public IConfigurationRoot Configuration { get; private set; }
                  
                      public Startup(IHostingEnvironment env)
                      {
                          var builder = new ConfigurationBuilder()
                              .SetBasePath(env.ContentRootPath)
                              .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                              .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                              .AddEnvironmentVariables();
                  
                          this.Configuration = builder.Build();
                      }
                      ...
                  }
                  


                  获取值

                  您可以通过多种方式获取从应用设置中配置的值:


                  Getting Values

                  There are many ways you can get the value you configure from the app settings:

                  • 使用ConfigurationBuilder.GetValue<T>
                  • 的简单方法
                  • 使用 选项模式

                  假设您的 appsettings.json 如下所示:

                  Let's say your appsettings.json looks like this:

                  {
                      "ConnectionStrings": {
                          ...
                      },
                      "AppIdentitySettings": {
                          "User": {
                              "RequireUniqueEmail": true
                          },
                          "Password": {
                              "RequiredLength": 6,
                              "RequireLowercase": true,
                              "RequireUppercase": true,
                              "RequireDigit": true,
                              "RequireNonAlphanumeric": true
                          },
                          "Lockout": {
                              "AllowedForNewUsers": true,
                              "DefaultLockoutTimeSpanInMins": 30,
                              "MaxFailedAccessAttempts": 5
                          }
                      },
                      "Recaptcha": { 
                          ...
                      },
                      ...
                  }
                  

                  简单方法

                  您可以将整个配置注入您的控制器/类的构造函数(通过 IConfiguration)并使用指定的键获取您想要的值:

                  Simple Way

                  You can inject the whole configuration into the constructor of your controller/class (via IConfiguration) and get the value you want with a specified key:

                  public class AccountController : Controller
                  {
                      private readonly IConfiguration _config;
                  
                      public AccountController(IConfiguration config)
                      {
                          _config = config;
                      }
                  
                      [AllowAnonymous]
                      public IActionResult ResetPassword(int userId, string code)
                      {
                          var vm = new ResetPasswordViewModel
                          {
                              PasswordRequiredLength = _config.GetValue<int>(
                                  "AppIdentitySettings:Password:RequiredLength"),
                              RequireUppercase = _config.GetValue<bool>(
                                  "AppIdentitySettings:Password:RequireUppercase")
                          };
                  
                          return View(vm);
                      }
                  }
                  

                  选项模式

                  如果您只需要应用设置中的一两个值,ConfigurationBuilder.GetValue<T> 非常有用.但是,如果您想从应用设置中获取多个值,或者您不想在多个位置对这些键字符串进行硬编码,那么使用 Options Pattern 可能会更容易.选项模式使用类来表示层次/结构.

                  Options Pattern

                  The ConfigurationBuilder.GetValue<T> works great if you only need one or two values from the app settings. But if you want to get multiple values from the app settings, or you don't want to hard code those key strings in multiple places, it might be easier to use Options Pattern. The options pattern uses classes to represent the hierarchy/structure.

                  使用选项模式:

                  1. 定义类来表示结构
                  2. 注册这些类绑定的配置实例
                  3. IOptions<T> 注入您要获取值的控制器/类的构造函数中
                  1. Define classes to represent the structure
                  2. Register the configuration instance which those classes bind against
                  3. Inject IOptions<T> into the constructor of the controller/class you want to get values on

                  1.定义配置类来表示结构

                  您可以定义具有需要完全匹配应用设置中的键的属性的类.类的名称不必与应用设置中的部分名称匹配:

                  1. Define configuration classes to represent the structure

                  You can define classes with properties that need to exactly match the keys in your app settings. The name of the class does't have to match the name of the section in the app settings:

                  public class AppIdentitySettings
                  {
                      public UserSettings User { get; set; }
                      public PasswordSettings Password { get; set; }
                      public LockoutSettings Lockout { get; set; }
                  }
                  
                  public class UserSettings
                  {
                      public bool RequireUniqueEmail { get; set; }
                  }
                  
                  public class PasswordSettings
                  {
                      public int RequiredLength { get; set; }
                      public bool RequireLowercase { get; set; }
                      public bool RequireUppercase { get; set; }
                      public bool RequireDigit { get; set; }
                      public bool RequireNonAlphanumeric { get; set; }
                  }
                  
                  public class LockoutSettings
                  {
                      public bool AllowedForNewUsers { get; set; }
                      public int DefaultLockoutTimeSpanInMins { get; set; }
                      public int MaxFailedAccessAttempts { get; set; }
                  }
                  

                  2.注册配置实例

                  然后你需要在启动的ConfigureServices()中注册这个配置实例:

                  using Microsoft.Extensions.Configuration;
                  using Microsoft.Extensions.DependencyInjection;
                  ...
                  
                  namespace DL.SO.UI.Web
                  {
                      public class Startup
                      {
                          ...
                          public void ConfigureServices(IServiceCollection services)
                          {
                              ...
                              var identitySettingsSection = 
                                  _configuration.GetSection("AppIdentitySettings");
                              services.Configure<AppIdentitySettings>(identitySettingsSection);
                              ...
                          }
                          ...
                      }
                  }
                  

                  3.注入 IOptions

                  最后在要获取值的控制器/类上,需要通过构造函数注入 IOptions:

                  public class AccountController : Controller
                  {
                      private readonly AppIdentitySettings _appIdentitySettings;
                  
                      public AccountController(IOptions<AppIdentitySettings> appIdentitySettingsAccessor)
                      {
                          _appIdentitySettings = appIdentitySettingsAccessor.Value;
                      }
                  
                      [AllowAnonymous]
                      public IActionResult ResetPassword(int userId, string code)
                      {
                          var vm = new ResetPasswordViewModel
                          {
                              PasswordRequiredLength = _appIdentitySettings.Password.RequiredLength,
                              RequireUppercase = _appIdentitySettings.Password.RequireUppercase
                          };
                  
                          return View(vm);
                      }
                  }
                  

                  这篇关于从 .net 核心中的 appsettings.json 获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  How to keep the Text of a Read only TextBox after PostBack()?(PostBack()之后如何保留只读文本框的文本?)
                  Winforms Textbox - Using Ctrl-Backspace to Delete Whole Word(Winforms 文本框 - 使用 Ctrl-Backspace 删除整个单词)
                  C# - Add button click events using code(C# - 使用代码添加按钮单击事件)
                  Multi-color TextBox C#(多色文本框 C#)
                  How can i set the caret position to a specific index in passwordbox in WPF(如何将插入符号位置设置为 WPF 密码框中的特定索引)
                  C# Numeric Only TextBox Control(C# 纯数字文本框控件)

                    <bdo id='6aTB3'></bdo><ul id='6aTB3'></ul>
                        <legend id='6aTB3'><style id='6aTB3'><dir id='6aTB3'><q id='6aTB3'></q></dir></style></legend>
                          <tbody id='6aTB3'></tbody>

                            <tfoot id='6aTB3'></tfoot>

                            <small id='6aTB3'></small><noframes id='6aTB3'>

                          1. <i id='6aTB3'><tr id='6aTB3'><dt id='6aTB3'><q id='6aTB3'><span id='6aTB3'><b id='6aTB3'><form id='6aTB3'><ins id='6aTB3'></ins><ul id='6aTB3'></ul><sub id='6aTB3'></sub></form><legend id='6aTB3'></legend><bdo id='6aTB3'><pre id='6aTB3'><center id='6aTB3'></center></pre></bdo></b><th id='6aTB3'></th></span></q></dt></tr></i><div id='6aTB3'><tfoot id='6aTB3'></tfoot><dl id='6aTB3'><fieldset id='6aTB3'></fieldset></dl></div>