jry
V2EX  ›  问与答

asp.net core 怎么读取 appsettings.json 整个数据为一个 JObject 吗

  •  
  •   jry · May 10, 2021 · 1429 views
    This topic created in 1898 days ago, the information mentioned may be changed or developed.

    官方文档只有读取简单的 string array object 结构,无法读取多个层次的数据整体。

    4 replies    2021-05-10 15:59:37 +08:00
    drunkdog
        1
    drunkdog  
       May 10, 2021
    又不一定非要用官方的,直接用 newtonJson 读 json 文件就好了呀
    Mithril
        2
    Mithril  
       May 10, 2021
    这东西不是简单的一个 JSON 文件,它是整个 app setting 框架的一部分。虽然你在程序里面使用 Configuration 的时候看起来像是从这个文件里读的,但实际上它可以从环境变量等地方传进来。
    而且 Configuration 本身可以读那里面的嵌套对象的,也可以直接反序列化,你定义个类型就行了。
    如果你非要弄个 JObject 的话那就 JSON.NET 直接读它就行了。
    h82258652
        3
    h82258652  
       May 10, 2021
    // appsettings.json
    {
    "Jry": {
    "Age": 18,
    "Name": "Jry"
    }
    }

    // JryOptions.cs
    public class JryOptions
    {
    public int Age{get;set;}
    public string Name{get;set;}
    }

    // Startup.cs
    public void ConfigureServices(ServiceCollection services)
    {
    // Other codes
    service.Config<JryOptions>("Jry");
    // Other codes
    }

    // YourController.cs ctor
    public YourController(IOptions<JryOptions> jryOptionsAccessor)
    {
    JryOptions options = jryOptionsAccessor.Value;
    }

    大概这样吧
    yejinmo
        4
    yejinmo  
       May 10, 2021
    用 dynamic 类型
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   988 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 22:09 · PVG 06:09 · LAX 15:09 · JFK 18:09
    ♥ Do have faith in what you're doing.