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:
- Add a reference to the
Microsoft.Extensions.Configuration
package in your project. - In your
Startup.cs
file, within theConfigureServices
method, add the following code to configure theIConfiguration
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...
}
- In your code, you can now access the values from the
appsettings.json
file by injecting theIConfiguration
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