van thanh tran
van thanh tran

Reputation: 177

Strongly typed AppSettings Configuration in ASP.NET 5

When using WebApi 2 my web.config was

<connectionStrings>
    <add name="RavenHQ" connectionString="Url=http://localhost:8080;Database=ModelFarmDb" />    
</connectionStrings>

For ASP.NET 5.0, I can't work out how to write the config.json file to do the same thing.

I've tried

{
    "Data": {
        "RavenHQ": {
            ConnectionString: "Url=http://localhost:8080;Database=ModelFarmDb"
        }
    }
}

but it doesn't work. Any suggestions on how to directly map the web.config sections to config.json so as not to break other libraries that assume a web.config?

The app is running under IIS Express locally and is a web app on Azure.

Many thanks!

Upvotes: 2

Views: 1337

Answers (1)

aidrivenpost
aidrivenpost

Reputation: 1943

You accomplish this in asp.net 5.0 in a different way. I used json file for this example. If you need add xml file just use these package Microsoft.Framework.Configuration.Xml and use .AddXmlFile() method

This example uses beta 7

Create an AppSetting class

public class AppSetting
{
    public string Setting1 { get; set; }

    public string Setting2 { get; set; }

}

In your startup file add the json file with the configuration on this example is call config.json

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{       

    var builder = new ConfigurationBuilder()
        .SetBasePath(appEnv.ApplicationBasePath)
        .AddJsonFile("config.json")
        .AddXmlFile("thefilename")
        .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);

    builder.AddEnvironmentVariables();

    Configuration = builder.Build();
}

public IConfiguration Configuration { get; set; }

Then you need to add the app service your AppSetting class so it can be injected for later use

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

Then in your controller or where ever you need the configuraton inject the IOptions<AppSettings>

public class SampleController : Controller
{

    private readonly AppSettings _appSettings;

    public SampleController(IOptions<AppSettings> appSettings)
    {            
        _appSettings = appSettings.Value;            
    }

}

and this is how the json looks like

{
  "AppSetting": {
    "Setting1": "Foo1",
    "Setting1": "Foo1"
  }
}

I took these peaces of code from live.asp.net in github

Upvotes: 2

Related Questions