0

I developed a code where I do some http request. I used to hard coded the url which i used for the http calls but i want to make it more efficient. What I did is:

Updated the appsettings.json file:

{

    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"

        }
    },
    "AllowedHosts": "*",
    "urls": "http://localhost:5002",
}

Added the urls field.

Created a field in the class where i want the url:

private readonly string _url = ConfigurationManager.AppSettings["urls"];

Program.cs class

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    webBuilder.UseUrls("http://localhost:5002");
                });
    }

In order to get the url from appsettings, and then pass the _url variable where i want to use it in the class. However for some reason im getting null value when im trying to run the program. Am I doing something wrong? and is there any better solution than that? Thank you in advance

Josh
  • 155
  • 1
  • 1
  • 9

2 Answers2

0

The way the appsettings.json loads into the app builder is different then .NET Framework. But this has been answered in another post. See How to read AppSettings values from a .json file in ASP.NET Core.

Kannan Mohan
  • 67
  • 1
  • 11
0

What you can do to avoid this problem is to use Microsoft.Extensions.Configuration class to retreive your data from appsettings.json .

Probably you will need also to inject the Configuration in your controller class as show below

private readonly IConfiguration _config;

public ConfigurationController(IConfiguration config)
{
    _config = config;
}

Now you can retrieve your data using the code below :

_config.GetValue<string>("urls");
sayah imad
  • 1,507
  • 3
  • 16
  • 24