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

编程入门 行业动态 更新时间:2024-10-19 14:49:56
本文介绍了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); }

在家庭控制器中

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

发布评论

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

>www.elefans.com

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