Extrayendo datos de appsetings.json en net core 5

Extrayendo datos de appsetings.json en net core 5

Crear solución

mkdir dummy && cd dummy

dotnet new sln

Crear proyecto

mkdir api && cd api

dotnet new webapi

Agregar proyecto a la solución

cd ..

dotnet sln add ./api/api.csproj

Crear modelo

cd api

mkdir Models && cd Models

touch Settings.cs
namespace api.Models
{
  public class Settings
  {
    public string param1 { get; set; }
    public string param2 { get; set; }
  }
}

Agregar valores en appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Settings": {
    "param1": "abc123",
    "param2": "def456"
  }
}

Registrar en Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  services.AddControllers();

  var section = Configuration.GetSection(nameof(Settings));
  var settings = section.Get<Settings>();
  services.AddSingleton(settings);

  services.AddSwaggerGen(c =>
  {
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "api", Version = "v1" });
  });
}

Inyectar dependencia en controlador

using Microsoft.AspNetCore.Mvc;
using api.Models;

namespace api.Controllers
{
  [ApiController]
  [Route("api")]
  public class TestController : ControllerBase
  {
    private readonly Settings _settings;

    public TestController(Settings settings)
    {
      _settings = settings;
    }

    [HttpGet]
    public string GetData()
    {
      return _settings.param1; // _settings.param2
    }
  }
}

Ejecutar api

dotnet run

http://localhost:5001/swagger