ASP.NET Core Get Json Array using IConfiguration

后端 未结 14 1983
失恋的感觉
失恋的感觉 2020-11-30 21:49

In appsettings.json

{
      \"MyArray\": [
          \"str1\",
          \"str2\",
          \"str3\"
      ]
}

In Startup.cs

相关标签:
14条回答
  • 2020-11-30 22:26

    Add a level in your appsettings.json :

    {
      "MySettings": {
        "MyArray": [
          "str1",
          "str2",
          "str3"
        ]
      }
    }
    

    Create a class representing your section :

    public class MySettings
    {
         public List<string> MyArray {get; set;}
    }
    

    In your application startup class, bind your model an inject it in the DI service :

    services.Configure<MySettings>(options => Configuration.GetSection("MySettings").Bind(options));
    

    And in your controller, get your configuration data from the DI service :

    public class HomeController : Controller
    {
        private readonly List<string> _myArray;
    
        public HomeController(IOptions<MySettings> mySettings)
        {
            _myArray = mySettings.Value.MyArray;
        }
    
        public IActionResult Index()
        {
            return Json(_myArray);
        }
    }
    

    You can also store your entire configuration model in a property in your controller, if you need all the data :

    public class HomeController : Controller
    {
        private readonly MySettings _mySettings;
    
        public HomeController(IOptions<MySettings> mySettings)
        {
            _mySettings = mySettings.Value;
        }
    
        public IActionResult Index()
        {
            return Json(_mySettings.MyArray);
        }
    }
    

    The ASP.NET Core's dependency injection service works just like a charm :)

    0 讨论(0)
  • 2020-11-30 22:26

    In ASP.NET Core 2.2 and later we can inject IConfiguration anywhere in our application like in your case, you can inject IConfiguration in HomeController and use like this to get the array.

    string[] array = _config.GetSection("MyArray").Get<string[]>();
    
    0 讨论(0)
提交回复
热议问题