Getting value from appsettings.json in .net core

In .NET Core, you can retrieve values from the appsettings.json file using the Configuration object provided by the Microsoft.Extensions.Configuration package. Here's how you can do it:

  1. Add a reference to the Microsoft.Extensions.Configuration package in your project.
  2. In your Startup.cs file, within the ConfigureServices method, add the following code to configure the IConfiguration object:
csharpCopy codeusing Microsoft.Extensions.Configuration;

public class Startup
{
    private IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // Configure the IConfiguration instance
        services.AddSingleton(Configuration);
        
        // Other service configurations...
    }

    // Other methods...
}
  1. In your code, you can now access the values from the appsettings.json file by injecting the IConfiguration object into your classes or methods. For example:
csharpCopy codeusing Microsoft.Extensions.Configuration;

public class MyClass
{
    private IConfiguration _configuration;

    public MyClass(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public void MyMethod()
    {
        // Access a value from the appsettings.json file
        var myValue = _configuration["MyKey"];
        
        // Other code...
    }
}

In the above code, MyKey represents the key of the value you want to retrieve from the appsettings.json file. Make sure the appsettings.json file is correctly configured with the key-value pairs you need.

Remember to build and run your application, ensuring that the appsettings.json file is located in the project's root directory or a subdirectory.


By  Junaid A    01-Dec-2023    2

Solutions


Your Answer

10352