How to access a global application.json variable in . NET Core c#

Asked

Viewed 111 times

0

I am new with programming and I’m having difficulty accessing a Token that is as variable in the file application.json. It is a console application, the goal is only to use the token of the global variable and use as a user to make an authentication in a GET method of an API. I don’t know what kind of prints I owe around here, I’ll put some down:

Application.json

{
  "Config": {
    "Environment": "Development",
    "ApiTokenSecretQA": "meuToken",
    "UrlApi": "https://api.mundipagg.com/core/v1"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"

Program.Cs

namespace Gateway_Pagamento
{
    class Program
    {
        static void Main(string[] args)
        {
            GetOrder.GetOrderId();

            //CreateHostBuilder(args).Build().Run();
        }


        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices(services =>
                {
                    services.AddHostedService<Worker>();
                });

Metodo Get Order - tried to do to access the API

public class GetOrder
    {
        [HttpGet]
        public static void GetOrderId()
        {
            Authenticator auth = new Authenticator();
            Authenticator.Authorization();

            try
            {
                var client = new RestClient("https://api.mundipagg.com/core/v1");
                //var request = new RestRequest(("orders/" + orderId), Method.GET, DataFormat.Json);
                var request = new RestRequest(("orders/"), Method.GET, DataFormat.Json);


                client.Authenticator = new HttpBasicAuthenticator(auth.BasicAuthUserName, auth.BasicAuthPassword);
                var response = client.Get(request);
                client.Execute(request);
                Console.WriteLine(response.Content);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
  • and where do you need to access it? on Main, Createhost or any other method?

  • @Ricardopunctual , is in a GET method, calling the API to query and authenticate, I will try to paste it above into the question.

1 answer

0


There are several ways to do this. In your example, you haven’t even created the Host yet, so you need to do it manually, like this:

public static void Main(string[] args)
{
    // Le o appsettings e criar um objeto IConfiguration
    var config = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", optional: false)
        .Build();

    // Lê o valor da chave 
    var token = config.GetSection("Config:ApiTokenSecretQA").Value;
 
    // Passa como parâmetro
    GetOrder.GetOrderId(token);
}

If you were doing this after creating the Host, you could do it in the Startup method as well

Now a more elegant way would be to create a class with the structure of its config and read all the config to a single object of that class, thus:

public class Configuracao  // se quiser injetar isso, pode adicionar uma interface
{
   public string Environment { get; set; }
   public string ApiTokenSecretQA { get; set; }
   public string UrlApi { get; set; }
}


// No Main
var minhaConfiguracao = config
    .GetSection("Config")
    .Get<Configuracao>();

GetOrder.GetOrderId(minhaConfiguracao);


public static void GetOrderId(Configuracao config)
    {
        Authenticator auth = new Authenticator();
        Authenticator.Authorization();

        try
        {
            var client = new RestClient(config.UrlApi);
            ....
  • It worked!! And thanks for the tip, I will try to implement here!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.