如何将appsetting.json部分加载到.NET Core中的Dictionary中?

编程入门 行业动态 更新时间:2024-10-25 19:34:55
本文介绍了如何将appsetting.json部分加载到.NET Core中的Dictionary中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我很熟悉将appsettings.json节加载到.NET Core startup.cs中的强类型对象中。例如:

I am familiar w/ loading an appsettings.json section into a strongly typed object in .NET Core startup.cs. For example:

public class CustomSection { public int A {get;set;} public int B {get;set;} } //In Startup.cs services.Configure<CustomSection>(Configuration.GetSection("CustomSection")); //Inject an IOptions instance public HomeController(IOptions<CustomSection> options) { var settings = options.Value; }

我有一个appsettings.json部分,其键/值对的数量会有所不同和名称随着时间的流逝。因此,对类中的属性名称进行硬编码是不切实际的,因为新的键/值对将需要在类中进行代码更改。以下是一些键/值对的小样本:

I have an appsettings.json section who's key/value pairs will vary in number and name over time. Therefore, it's not practical to hard code property names in a class since new key/value pairs would require a code change in the class. A small sample of some key/value pairs:

"MobileConfigInfo": { "appointment-confirmed": "We've booked your appointment. See you soon!", "appointments-book": "New Appointment", "appointments-null": "We could not locate any upcoming appointments for you.", "availability-null": "Sorry, there are no available times on this date. Please try another." }

是否可以将这些数据加载到MobileConfigInfo Dictionary对象中,然后使用是否可以通过IOptions模式将MobileConfigInfo注入到控制器中?

Is there a way to load this data into a MobileConfigInfo Dictionary object and then use the IOptions pattern to inject MobileConfigInfo into a controller?

推荐答案

您可以使用 Configuration.Bind(settings) ; 在 startup.cs 类中

您的设置类将类似于

public class AppSettings { public Dictionary<string, string> MobileConfigInfo { get; set; } }

希望它会有所帮助!

更多推荐

如何将appsetting.json部分加载到.NET Core中的Dictionary中?

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

发布评论

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

>www.elefans.com

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