【问题标题】:Confusion between .config files and Azure settings on ASP.Net core web app.config 文件和 ASP.Net 核心 Web 应用程序上的 Azure 设置之间的混淆
【发布时间】:2017-07-12 14:25:59
【问题描述】:

我已经构建了一个项目(为 SPA Web 应用程序提供 API)作为带有 WebApi 选项(VS 2017 社区)的 Asp.Net Core Web 应用程序(.net 框架)。这创建了一个带有 app.config 文件但没有 web.config 文件的项目。我在 app.config 中有一个部分,我在 Startup.cs 类中使用 System.Configuration.ConnectionManager.ConnectionStrings['MainDb'] 阅读了该部分,该部分在本地运行良好。

当我将应用程序部署到 Azure 并在门户中设置“MainDb”连接字符串时,Web 应用程序不会读取它。我已经通过门户直接设置了这些,也通过 VS2017 中的 Azure 服务器资源管理器提供的设置窗格进行了设置。在服务器资源管理器中,我可以看到 web.config 文件但没有 app.config 文件,web.config 文件没有 connectionstring 节点,但 Web 应用程序似乎看到了我部署时 app.config 中的连接字符串。

我对 app.config 和 web.config 之间的交互感到有些困惑 - 我需要在哪里声明我的连接字符串,以便它可以被 Azure 门户设置覆盖?

【问题讨论】:

  • 我以为模板会创建一个 appsettings.json 文件?
  • 是的,确实如此。看起来项目是作为一个“空”项目开始的,而不是一个网络应用程序和添加到其中的东西。那么连接字符串应该放在 appsettings 中吗?
  • 是的,应该。您可以查看我写的这篇文章以获得更多指导:joonasw.net/view/asp-net-core-1-configuration-deep-dive。您应该将它添加到 ConnectionStrings 部分,并使用核心配置 API 而不是您正在使用的 API 来阅读它。
  • 我在项目中添加了一个 appsettings.json 文件并将我的连接字符串放在那里; app.config 不再使用。按照 junnas 文章中的建议再次阅读它们是可行的,并且它们按预期在 Azure 中被拾取。
  • 太好了:)我会回答的。

标签: azure asp.net-web-api


【解决方案1】:

通常在 ASP.NET Core 中,我们使用 appsettings.json 文件进行配置。尽管还有许多其他选项(XML、用户机密等):https://joonasw.net/view/asp-net-core-1-configuration-deep-dive

所以你会有一个这样的 appsettings.json 文件:

{
  "ConnectionStrings": {
    "MainDb": "Data Source=.;Initial Catalog=MainDb;Integrated Security=True"
  }
}

然后您可以通过访问Startup 中的IConfiguration 对象来读取它:

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")实际上是Configuration.GetSection("ConnectionStrings")["name"]的简写。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-17
    • 2011-09-27
    • 1970-01-01
    • 2010-12-29
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多