0

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

0

1 Answer 1

0

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:

enter image description here

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:

enter image description here

You can read Configuration in ASP.NET Core to know more.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.