微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-core – ASP.NET核心MVC应用程序设置

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

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

>创建了一个appsettings.json
>创建了一个AppSettings类
>现在我正在尝试将其注入到ConfigureServices上,但我的Configuration类无法识别或使用完整引用:“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文件获取数据,首先需要在Startup.cs中设置ConfigurationBuilder,如下所示:

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

然后,您可以直接访问配置,但创建选项类来保存该数据更为全面,然后您可以将这些数据注入控制器或其他类.每个选项类都代表appsettings.json文件的不同部分.

在此代码中,连接字符串被加载到ConnectionStringSettings类中,另一个选项被加载到MyOptions类中. .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注入控制器来访问这些设置,如下所示:

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.

原文地址:https://www.jb51.cc/aspnet/245496.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐