【发布时间】: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