ASP.NET Core Obtenga Json Array usando IConfiguration

168

En appsettings.json

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

En Startup.cs

public void ConfigureServices(IServiceCollection services)
{
     services.AddSingleton<IConfiguration>(Configuration);
}

En HomeController

public class HomeController : Controller
{
    private readonly IConfiguration _config;
    public HomeController(IConfiguration config)
    {
        this._config = config;
    }

    public IActionResult Index()
    {
        return Json(_config.GetSection("MyArray"));
    }
}

Hay mis códigos arriba, obtuve un valor nulo ¿Cómo obtener la matriz?

Max
fuente

Respuestas:

103

Si desea elegir el valor del primer elemento, entonces debe hacer esto:

var item0 = _config.GetSection("MyArray:0");

Si desea elegir el valor de toda la matriz, entonces debe hacer así:

IConfigurationSection myArraySection = _config.GetSection("MyArray");
var itemArray = myArraySection.AsEnumerable();

Idealmente, debería considerar usar el patrón de opciones sugerido por la documentación oficial. Esto te dará más beneficios.

Sanket
fuente
23
Si tiene una matriz de objetos como "Clients": [ {..}, {..} ], debe invocar Configuration.GetSection("Clients").GetChildren().
halllo
40
Si tiene una serie de literales como "Clients": [ "", "", "" ], debe invocar .GetSection("Clients").GetChildren().ToArray().Select(c => c.Value).ToArray().
halllo
66
Esta respuesta realmente producirá 4 elementos, el primero es la sección misma con un valor vacío. Es incorrecto
Giovanni Bassi
44
Lo var clients = Configuration.GetSection("Clients").GetChildren() .Select(clientConfig => new Client { ClientId = clientConfig["ClientId"], ClientName = clientConfig["ClientName"], ... }) .ToArray();
invoqué con
1
Ninguna de estas opciones funciona para mí, ya que el objeto vuelve a ser nulo en el punto de "Clientes" usando el ejemplo de Hallo. Estoy seguro de que el json está bien formado, ya que funciona con el desplazamiento insertado en la cadena ["item: 0: childItem"] en el formato "Item": [{...}, {...}]
Clarence
283

Puede instalar los siguientes dos paquetes NuGet:

Microsoft.Extensions.Configuration    
Microsoft.Extensions.Configuration.Binder

Y luego tendrá la posibilidad de utilizar el siguiente método de extensión:

var myArray = _config.GetSection("MyArray").Get<string[]>();
Razvan Dumitru
fuente
13
Esto es mucho más directo que las otras respuestas.
jao
14
Esta es la mejor respuesta con diferencia.
Giovanni Bassi
15
En mi caso, la aplicación web Aspnet core 2.1 incluía estos dos paquetes nuget. Así que fue solo un cambio de línea. Gracias
Shibu Thannikkunnath
¡El más simple!
Pablo
3
También funciona con una variedad de objetos, por ejemplo _config.GetSection("AppUser").Get<AppUser[]>();
Giorgos Betsos
60

Agregue un nivel en su appsettings.json:

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

Crea una clase que represente tu sección:

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

En la clase de inicio de su aplicación, vincule su modelo e inyéctelo en el servicio DI:

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

Y en su controlador, obtenga sus datos de configuración del servicio DI:

public class HomeController : Controller
{
    private readonly List<string> _myArray;

    public HomeController(IOptions<MySettings> mySettings)
    {
        _myArray = mySettings.Value.MyArray;
    }

    public IActionResult Index()
    {
        return Json(_myArray);
    }
}

También puede almacenar su modelo de configuración completo en una propiedad en su controlador, si necesita todos los datos:

public class HomeController : Controller
{
    private readonly MySettings _mySettings;

    public HomeController(IOptions<MySettings> mySettings)
    {
        _mySettings = mySettings.Value;
    }

    public IActionResult Index()
    {
        return Json(_mySettings.MyArray);
    }
}

El servicio de inyección de dependencias de ASP.NET Core funciona de maravilla :)

AdrienTorris
fuente
Entonces, ¿cómo se usa MySettingsen el inicio?
T.Coutlakis
Recibo un error que dice que necesita una coma entre "MySettings" y "MyArray".
Markus
35

Si tiene una matriz de objetos JSON complejos como este:

{
  "MySettings": {
    "MyValues": [
      { "Key": "Key1", "Value":  "Value1" },
      { "Key": "Key2", "Value":  "Value2" }
    ]
  }
}

Puede recuperar la configuración de esta manera:

var valuesSection = configuration.GetSection("MySettings:MyValues");
foreach (IConfigurationSection section in valuesSection.GetChildren())
{
    var key = section.GetValue<string>("Key");
    var value = section.GetValue<string>("Value");
}
Dmitry Pavlov
fuente
30

Esto funcionó para mí para devolver una serie de cadenas de mi configuración:

var allowedMethods = Configuration.GetSection("AppSettings:CORS-Settings:Allow-Methods")
    .Get<string[]>();

Mi sección de configuración se ve así:

"AppSettings": {
    "CORS-Settings": {
        "Allow-Origins": [ "http://localhost:8000" ],
        "Allow-Methods": [ "OPTIONS","GET","HEAD","POST","PUT","DELETE" ]
    }
}
CodeThief
fuente
15

Para el caso de devolver una matriz de objetos JSON complejos desde la configuración, he adaptado la respuesta de @ djangojazz para usar tipos anónimos y dinámicos en lugar de tuplas.

Dada una sección de configuración de:

"TestUsers": [
{
  "UserName": "TestUser",
  "Email": "[email protected]",
  "Password": "P@ssw0rd!"
},
{
  "UserName": "TestUser2",
  "Email": "[email protected]",
  "Password": "P@ssw0rd!"
}],

Puede devolver la matriz de objetos de esta manera:

public dynamic GetTestUsers()
{
    var testUsers = Configuration.GetSection("TestUsers")
                    .GetChildren()
                    .ToList()
                    .Select(x => new {
                        UserName = x.GetValue<string>("UserName"),
                        Email = x.GetValue<string>("Email"),
                        Password = x.GetValue<string>("Password")
                    });

    return new { Data = testUsers };
}
jaycer
fuente
Esto es increíble
Vladimir Demirev
11

Es una pregunta antigua, pero puedo dar una respuesta actualizada para .NET Core 2.1 con los estándares C # 7. Digamos que tengo una lista solo en appsettings.Development.json como:

"TestUsers": [
  {
    "UserName": "TestUser",
    "Email": "[email protected]",
    "Password": "P@ssw0rd!"
  },
  {
    "UserName": "TestUser2",
    "Email": "[email protected]",
    "Password": "P@ssw0rd!"
  }
]

Puedo extraerlos en cualquier lugar donde Microsoft.Extensions.Configuration.IConfiguration esté implementado y conectado de la siguiente manera:

var testUsers = Configuration.GetSection("TestUsers")
   .GetChildren()
   .ToList()
    //Named tuple returns, new in C# 7
   .Select(x => 
         (
          x.GetValue<string>("UserName"), 
          x.GetValue<string>("Email"), 
          x.GetValue<string>("Password")
          )
    )
    .ToList<(string UserName, string Email, string Password)>();

Ahora tengo una lista de un objeto bien escrito que está bien escrito. Si voy a testUsers.First (), Visual Studio debería mostrar ahora las opciones para 'Nombre de usuario', 'Correo electrónico' y 'Contraseña'.

djangojazz
fuente
9

En ASP.NET Core 2.2 y versiones posteriores, podemos inyectar IConfiguration en cualquier lugar de nuestra aplicación, como en su caso, puede inyectar IConfiguration en HomeController y usarlo de esta manera para obtener la matriz.

string[] array = _config.GetSection("MyArray").Get<string[]>();
arenoso
fuente
5

Puede obtener la matriz directa sin incrementar un nuevo nivel en la configuración:

public void ConfigureServices(IServiceCollection services) {
    services.Configure<List<String>>(Configuration.GetSection("MyArray"));
    //...
}
Andreas Friedel
fuente
4

Forma corta:

var myArray= configuration.GetSection("MyArray")
                        .AsEnumerable()
                        .Where(p => p.Value != null)
                        .Select(p => p.Value)
                        .ToArray();

Devuelve una matriz de cadena:

{"str1", "str2", "str3"}

mojtaba karimi
fuente
1
Trabajó para mi. Gracias. El uso de Microsoft.Extensions.Configuration.Binder también funciona, sin embargo, me gustaría evitar hacer referencia a otro paquete Nuget si una sola línea de código puede hacer el trabajo.
Sau001
3

Esto funcionó para mí; Crea un archivo json:

{
    "keyGroups": [
        {
            "Name": "group1",
            "keys": [
                "user3",
                "user4"
            ]
        },
        {
            "Name": "feature2And3",
            "keys": [
                "user3",
                "user4"
            ]
        },
        {
            "Name": "feature5Group",
            "keys": [
                "user5"
            ]
        }
    ]
}

Luego, defina alguna clase que asigne:

public class KeyGroup
{
    public string name { get; set; }
    public List<String> keys { get; set; }
}

paquetes nuget:

Microsoft.Extentions.Configuration.Binder 3.1.3
Microsoft.Extentions.Configuration 3.1.3
Microsoft.Extentions.Configuration.json 3.1.3

Luego, cárguelo:

using Microsoft.Extensions.Configuration;
using System.Linq;
using System.Collections.Generic;

ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

configurationBuilder.AddJsonFile("keygroup.json", optional: true, reloadOnChange: true);

IConfigurationRoot config = configurationBuilder.Build();

var sectionKeyGroups = 
config.GetSection("keyGroups");
List<KeyGroup> keyGroups = 
sectionKeyGroups.Get<List<KeyGroup>>();

Dictionary<String, KeyGroup> dict = 
            keyGroups = keyGroups.ToDictionary(kg => kg.name, kg => kg);
Roland Roos
fuente