Custom section/collection in Web.Config

这一生的挚爱 提交于 2019-12-03 12:15:49
Richard

Yes. And not too hard once you have a start.

You'll need to create a ConfigurationSection derived class to define the <routes> section (and then add a <section> to the configuration to link the <routes> element to your type).

You'll then need a type to define each element of the collection and, flagged as default, a property on your second type for the collection.

After all this is set up, at runtime you access your configuration section as:

var myRoutes = ConfigurationManager.GetSection("routes") as RoutesConfigSection;

My blog has a few articles on the background to this: http://blog.rjcox.co.uk/category/dev/net-core/

As noted in another answer there is also coverage (a lot better than it used to be) on MSDN.

If you don't want to create a class to represent your config section you can do this:

var configSection = ConfigurationManager.GetSection("sectionGroup/sectionName");
var aValue = (configSection as dynamic)["ValueKey"];

Converting to dynamic lets you access the key values in configSection. You may have to add a break point and peak in configSection to see what is there and what ValueKey to use.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!