Inn the way the web.config file can be accessed through using System.Configuration.ConfigurationManager
in asp.net, is there a way to access values in the appsettings.json file like so, without the need to use to inject any services ? I realize that the web.config file is no longer in use as much in .net core, I just wanted to know whether there was a similar method that could be used to access values from appsettings.json
Yes, you can also use the configuration directly, appsettings are injected so you can get to them with DI.
Option 1
You can try below code in the Program.cs(asp.net core 6+) to access values from appsettings.json:
var builder = WebApplication.CreateBuilder(args);
var vv = builder.Configuration.GetValue<string>("value");
...
In appsettings.json:
{"Value":"aaa"}
result:
Option 2
In your controller:
public class OPController : Controller
{
private readonly IConfiguration _configuration;
public OPController(IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult Index()
{
var vv = _configuration.GetSection("value").Get<string>();
return View();
}
}
result:
You can read Configuration in ASP.NET Core to know more.