asp.net-core - ASP.NET Core MVC 应用设置

标签 asp.net-core asp.net-core-mvc

我正在尝试在我的 ASP.NET Core MVC 项目中使用配置变量。

这是我到目前为止的地方:

  • 创建了一个 appsettings.json
  • 创建了一个 AppSettings 类
  • 现在我试图将它注入(inject)到 ConfigureServices 上,但我的配置类要么无法识别,要么在使用完整引用时:“Microsoft.Extensions.Configuration”无法识别 GetSection 方法,即

  • Configuration class not being recognized

    GetSection method not being recognized

    关于如何使用它的任何想法?

    最佳答案

    .NET Core 中的整个配置方法非常灵活,但一开始并不明显。用一个例子来解释可能最容易:

    假设 appsettings.json 文件如下所示:

    {
      "option1": "value1_from_json",
    
      "ConnectionStrings": {
        "DefaultConnection": "Server=,\\SQL2016DEV;Database=DBName;Trusted_Connection=True"
      },
      "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
          "Default": "Warning"
        }
      }
    }
    

    要从 appsettings.json 文件中获取数据,您首先需要设置 ConfigurationBuilder在 Startup.cs 中如下:
    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);
    
        if (env.IsDevelopment())
        {
            // For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
            builder.AddUserSecrets<Startup>();
        }
    
        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    

    然后您可以直接访问配置,但是创建选项类来保存该数据会更简洁,然后您可以将其注入(inject) Controller 或其他类。这些选项类中的每一个都代表 appsettings.json 文件的不同部分。

    在这段代码中,连接字符串被加载到 ConnectionStringSettings 中。类和另一个选项加载到 MyOptions类(class)。 .GetSection方法获取 appsettings.json 文件的特定部分。同样,这是在 Startup.cs 中:
    public void ConfigureServices(IServiceCollection services)
    {
        ... other code
    
        // Register the IConfiguration instance which MyOptions binds against.
        services.AddOptions();
    
        // Load the data from the 'root' of the json file
        services.Configure<MyOptions>(Configuration);
    
        // load the data from the 'ConnectionStrings' section of the json file
        var connStringSettings = Configuration.GetSection("ConnectionStrings");
        services.Configure<ConnectionStringSettings>(connStringSettings);
    

    这些是加载设置数据的类。请注意属性名称如何与 json 文件中的设置配对:
    public class MyOptions
    {
        public string Option1 { get; set; }
    }
    
    public class ConnectionStringSettings
    {
        public string DefaultConnection { get; set; }
    }
    

    最后,您可以通过将 OptionsAccessor 注入(inject) Controller 来访问这些设置,如下所示:
    private readonly MyOptions _myOptions;
    
    public HomeController(IOptions<MyOptions > optionsAccessor)
    {
        _myOptions = optionsAccessor.Value;
        var valueOfOpt1 = _myOptions.Option1;
    }
    

    一般来说,整个配置设置过程在 Core 中是完全不同的。 Thomas Ardal 在他的网站上有一个很好的解释:http://thomasardal.com/appsettings-in-asp-net-core/

    Configuration in ASP.NET Core in the Microsoft documentation还有更详细的解释.

    注意:这一切在 Core 2 中都发生了一些变化,我需要重新审视上面的一些答案,但与此同时 this Coding Blast entry by Ibrahim Šuta是一个很好的介绍,有很多例子。

    NB No. 2:上面有很多容易犯的配置错误,看看this answer如果它不适合你。

    关于asp.net-core - ASP.NET Core MVC 应用设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43448993/

    相关文章:

    asp.net - 在.NET Core中更新身份登录页面的默认前端设计

    c# - 如何对 HttpContext.SignInAsync() 进行单元测试?

    javascript - 如何停止Requiredfieldvalidator在取消点击时工作

    javascript - .NET Core 如何使用 AJAX 提交带有文件的表单?

    asp.net-core - IWebHost WebHostBuilder BuildWebHost 有什么区别

    c# - 如何在 ASP.NET Core 中转换 AppSettings

    c# - 如何检查 MVC Core 配置文件中的某个部分是否存在?

    asp.net-core - 我可以提交 MVC6 View 组件吗?

    asp.net-core-mvc - 使用 FluentScheduler - ASP.NET Core MVC

    c# - 在 'TContext' 上找不到无参数构造函数