How to read AppSettings values from .json file in

2019-01-03 13:06发布

I have setup my AppSettings data in appsettings/Config .json like this:

{
  "AppSettings": {
        "token": "1234"
    }
}

I have searched online on how to read AppSettings values from .json file, but I could not get anything useful.

I tried:

var configuration = new Configuration();
var appSettings = configuration.Get("AppSettings"); // null
var token = configuration.Get("token"); // null

I know with ASP.NET 4.0 you can do this:

System.Configuration.ConfigurationManager.AppSettings["token"];

But how do I do this in ASP.NET Core?

11条回答
何必那么认真
2楼-- · 2019-01-03 13:19

First off: The assembly name and namespace of Microsoft.Framework.ConfigurationModel has changed to Microsoft.Framework.Configuration. So you should use: e.g.

"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"

as a dependency in project.json. Use beta5 or 6 if you don't have 7 installed. Then you can do something like this in Startup.cs.

public IConfiguration Configuration { get; set; }

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
     var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
        .AddJsonFile("config.json")
        .AddEnvironmentVariables();
     Configuration = configurationBuilder.Build();
}

If you then want to retrieve a variable from the config.json you can get it right away using:

public void Configure(IApplicationBuilder app)
    {
        // Add .Value to get the token string
        var token = Configuration.GetSection("AppSettings:token");
        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("This is a token with key (" + token.Key + ") " + token.Value);
        });
    }

or you can create a class called AppSettings like this:

public class AppSettings
{
    public string token { get; set; }
}

and configure the services like this:

public void ConfigureServices(IServiceCollection services)
{       
    services.AddMvc();

    services.Configure<MvcOptions>(options =>
    {
        //mvc options
    });

    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}

and then access it through e.g. a controller like this:

public class HomeController : Controller
{
    private string _token;

    public HomeController(IOptions<AppSettings> settings)
    {
        _token = settings.Options.token;
    }
}
查看更多
狗以群分
3楼-- · 2019-01-03 13:27

So I doubt this is good practice but it's working locally, I'll update this if it fails when I publish/deploy (to an IIS web service).

Step 1.) Add this assembly to the top of your class (in my case, controller class):

using Microsoft.Extensions.Configuration;

Step 2.) Add this or something like it:

var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json").Build();

Step 3.) Call your key's value by doing this (returns string):

config["NameOfYourKey"]

查看更多
不美不萌又怎样
4楼-- · 2019-01-03 13:28

Just to complement the Yuval Itzchakov answer.

You can load configuration without builder function, you can just inject it.

public IConfiguration Configuration { get; set; }

public Startup(IConfiguration configuration)
{
   Configuration = configuration;
}
查看更多
Ridiculous、
5楼-- · 2019-01-03 13:31

If you just want to get the value of the token then use

Configuration["AppSettings:token"]

查看更多
神经病院院长
6楼-- · 2019-01-03 13:36

Was this "cheating"? I just made my Configuration in the Startup class static, and then I can access it from anywhere else:

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        Configuration = builder.Build();
    }

    public static IConfiguration Configuration { get; set; }
查看更多
Rolldiameter
7楼-- · 2019-01-03 13:37

Following works for Console Apps;

1- install following nuget packages (.csproj);

<ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0-preview2-35157" />
    <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0-preview2-35157" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0-preview2-35157" />
  </ItemGroup>

2- Create appsettings.json at root level. Right click on it and "Copy to Output Directory" as "Copy if newer".

3- Sample config file:

{
  "AppConfig": {
    "FilePath": "C:\\temp\\logs\\output.txt"
  }
}

4- Program.cs

configurationSection.Key and configurationSection.Value will have config properties.

static void Main(string[] args)
{
    try
    {

        IConfigurationBuilder builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

        IConfigurationRoot configuration = builder.Build();
        // configurationSection.Key => FilePath
        // configurationSection.Value => C:\\temp\\logs\\output.txt
        IConfigurationSection configurationSection = configuration.GetSection("AppConfig").GetSection("FilePath");  

    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
}
查看更多
登录 后发表回答