Reputation: 4564
I have built a project (to provide an API to a SPA web app) as a Asp.Net Core Web Application (.net framework) with the WebApi option (VS 2017 Community). This created a project with an app.config file and no web.config file. I have a section in app.config that I read using System.Configuration.ConnectionManager.ConnectionStrings['MainDb']
in my Startup.cs class which works fine locally.
When I deploy the app to Azure and set a 'MainDb' connection string in the portal, it does not get read by the web app. I have set these via the portal directly and via the settings pane available via the Azure server explorer in VS2017. In the server explorer I can see a web.config file but no app.config file, the web.config file has no connectionstring node but the web app seems to be seeing the connection string that was in app.config when I deployed.
I am somewhat confused as to the interaction between the app.config and the web.config here - where do I need to declare my connection string so that it can be overridden by the Azure portal setting?
Upvotes: 1
Views: 266
Reputation: 58733
Typically in ASP.NET Core we use an appsettings.json
file for configuration. Though there are many other options too (XML, user secrets etc.): https://joonasw.net/view/asp-net-core-1-configuration-deep-dive.
So you would have an appsettings.json file like this:
{
"ConnectionStrings": {
"MainDb": "Data Source=.;Initial Catalog=MainDb;Integrated Security=True"
}
}
You can then read it by accessing the IConfiguration
object in Startup
:
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public IConfiguration Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
string connStr = Configuration.GetConnectionString("MainDb);
}
}
GetConnectionString("name")
is actually a shorthand for Configuration.GetSection("ConnectionStrings")["name"]
.
Upvotes: 1