【问题标题】:Retrieving data from appsettings.json从 appsettings.json 检索数据
【发布时间】:2019-01-31 17:25:19
【问题描述】:

所以我真的被困了 2 天。我一直在通过stackoverflow和google搜索许多指南,但没有帮助:/。所以我试图从 appsettings json 文件中检索数据,因为我会将数据作为标准设置文件存储在其中。

我想读取一个 json 数组-> iv' 将我的部分称为“位置”和我的键“位置”,其中我的值是一个 json 数组。目前,该数组中只有汽车公司名称,而不是真实数据。真正的数据是文件路径。

我正在使用带有 .net core 2.0 或 2.1 的 vs2017

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

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)
{
    services.AddMvc()
        .AddJsonOptions(config =>
        {
            config.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        });
    services.AddOptions();
    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)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddEnvironmentVariables()
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();

    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    Configuration = builder.Build();
}

这是我的创业课程。

"Locations": {
    "Location": [ "Ford", "BMW", "Fiat" ]
}, 

我的 json。

namespace MediaCenter.Models
{
    public class Locations
    {
        public List<string> location { get; set; }
    }
}

我的课,因为我读到 .net core 2.0 需要 DI 系统。

public IActionResult Settings()
{
    var array = _configuration.GetSection("Locations").GetSection("Location");
    var items = array.Value.AsEnumerable();
    return View();
}

我的控制器数据。

作为记录,当我在“var 数组”处创建断点时,我可以在提供程序和成员中看到我的值存储在其中,所以我想我没有正确调用数组?无论如何,如果我得到一个很好的工作答案,那真的会有所帮助,因为我被卡住了:(。

【问题讨论】:

    标签: c# .net asp.net-mvc asp.net-core dependency-injection


    【解决方案1】:

    有几件事是错误的。

    1. 在你的启动中你需要配置Configuration 构造函数不在 ConfigureServices(services) 中。
    2. 它们被存储为Children,所以你需要做GetChildren() on 你的部分。

    这是您需要在Startup.cs中更改的内容

    // Replace IConfiguration with IHostingEnvironment since we will build
    // Our own configuration
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddEnvironmentVariables()
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
    
        // Set the new Configuration
        Configuration = builder.Build();
    }
    

    在您的控制器中,您现在可以使用以下内容:

    public IActionResult Settings()
    {
       var array = Configuration.GetSection("Locations:Location")
           .GetChildren()
           .Select(configSection => configSection.Value);
       return View();
    } 
    

    编辑

    问题是 appsettings.json 格式不正确。一切都被配置为Logging 部分的子项。下面是更新和正确的 json,我添加了一个额外的 }, 并从底部删除了 }

     {
      "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
          "Default": "Warning"
        }
      },
    
      "DBConnection": {
        "Host": "",
        "UserName": "",
        "Password": ""
      },
    
      "Locations": {
        "Location": [ "Ford", "BMW", "Fiat" ]
      },
    
      "VideoExtensions": {
        "Extensions": []
      }
    }
    

    【讨论】:

    • 好吧,这是一个很好的例子,但仍然无效。我的创业班一切都好吗?
    • @TimClinckemalie 你是对的,你的启动课程也错了,看看我编辑的答案!
    • 我仍然有问题,我已经把它放在启动但仍然得到“空”:/对不起,如果它太多,问仍然学习困难。代码:pastebin.com/Z7smP40a
    • @TimClinckemalie 我刚刚创建了一个新项目,其中只有您的代码,它对我有用,不确定问题可能是什么。也许您可以将整个项目上传到 github?
    • 我的项目已上传到我的私人 gitlab 服务器上,但我也许可以将其迁移到公共 github
    【解决方案2】:

    对于Program.cs中的WebHost.CreateDefaultBuilder,不需要使用new ConfigurationBuilder()。尝试以下选项:

    Option1IConfiguration获取值

        public class OptionsController : Controller
    {
        private readonly IConfiguration _configuration;
    
        public OptionsController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        public IActionResult Index()
        {
            var locations = new Locations();
            _configuration.GetSection("Locations").Bind(locations);
    
            var items = locations.location.AsEnumerable();
            return View();
        }
    }
    

    选项Startup中配置Options

    1. 启动.cs

              services.Configure<Locations>(Configuration.GetSection("Locations"));
      
    2. 在控制器中使用

      public class OptionsController : Controller
      {
      private readonly Locations _locations;
      public OptionsController(IOptions<Locations> options)
      {
          _locations = options.Value;
      }
      public IActionResult Index()
      {           
          var items2 = _locations;
          return View();
      }
       }
      

    Source Code

    【讨论】:

    • 好吧,当我设置断点时,它对我来说仍然是“null”。或者我做错了什么或者我不知道。
    • @TimClinckemalie 你下载源代码做测试了吗?
    • 是的,但是当我查看 _location 时仍然是“空”,它说是空数组。但也许永远不会把它留在这里。我在这里和谷歌上找到了很多指南,尽管你们试图帮助我,但它似乎不起作用。所以我只使用一个可能比 appsettings 更好的 db,但还是谢谢
    • @TimClinckemalie 你能分享一下你的_locations的屏幕截图吗?
    • @TimClinckemalie 屏幕截图似乎是您自己的项目。下载我的项目而不是复制源代码?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 2014-12-12
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多