ASP.NET Core使用IConfiguration获取Json数组

编程入门 行业动态 更新时间:2024-10-19 08:50:51
本文介绍了ASP.NET Core使用IConfiguration获取Json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在appsettings.json中

In appsettings.json

{ "MyArray": [ "str1", "str2", "str3" ] }

在Startup.cs

In Startup.cs

public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IConfiguration>(Configuration); }

在HomeController中

In HomeController

public class HomeController : Controller { private readonly IConfiguration _config; public HomeController(IConfiguration config) { this._config = config; } public IActionResult Index() { return Json(_config.GetSection("MyArray")); } }

上面有我的代码,我为空 如何获得数组?

There are my codes above, I got null How to get the array?

推荐答案

如果要选择第一项的值,则应该这样做-

If you want to pick value of first item then you should do like this-

var item0 = _config.GetSection("MyArray:0");

如果要选择整个数组的值,则应该这样做-

If you want to pick value of entire array then you should do like this-

IConfigurationSection myArraySection = _config.GetSection("MyArray"); var itemArray = myArraySection.AsEnumerable();

理想情况下,您应该考虑使用选项文件,由官方文档建议.这将为您带来更多好处.

Ideally, you should consider using options pattern suggested by official documentation. This will give you more benefits.

更多推荐

ASP.NET Core使用IConfiguration获取Json数组

本文发布于:2023-11-14 15:04:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587684.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   NET   ASP   Core   Json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!