Microsoft.Configuration.Extensions: How to get section / complex value as json string?

送分小仙女□ 提交于 2021-01-29 10:59:32

问题


When we have configuration like this

// appsettings.json
{
    "SomeServiceConfiguration": {
       "Server": "127.0.0.1",
       "Port": "25"
    }
}

it is possible to use binding to access data:

IConfiguration configuration =  ...;
var section = configuration.GetSection("SomeServiceConfiguration");
var val = section.Value; // this is null
var t = new SomeServiceConfiguration();
section.Bind(t);

But is it possible to get value (section content) "just as string" (by the fact as json) {"Server": "127.0.0.1", "Port": "25"} ?


回答1:


According to ConfigurationSection Class this is not directly possible.

However, you could serialize to XML using the ConfigurationElement.SerializeElement(XmlWriter, Boolean) Method, which is possible by default. You would have to convert to JSON afterwards, so this seems overkill.

I would recommend building a new JSON Object and accessing the section values directly.



来源:https://stackoverflow.com/questions/52012599/microsoft-configuration-extensions-how-to-get-section-complex-value-as-json-s

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