1
votes

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?

1
I thought the template creates an appsettings.json file?juunas
Yeah, it does. Looks like project was started as an 'Empty' one rather than a web app and stuff added to it. Should the connection strings go in appsettings then?Rikalous
Yeah, it should. You can check this article I wrote for more guidance: joonasw.net/view/asp-net-core-1-configuration-deep-dive. You should add it to a ConnectionStrings section, and read it using the Core configuration APIs instead of the one you were using.juunas
I added an appsettings.json file to the project and placed my connection strings in there; app.config no longer used. Following the advice in junnas's article to read them out again worked and they are picked up in Azure as expected.Rikalous
Great :) I'll make an answer.juunas

1 Answers

1
votes

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"].