entity-framework-6 - ASP.NET 5 中的强类型 AppSettings 配置

标签 entity-framework-6 asp.net-core

使用 WebApi 2 时,我的 web.config 是

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

对于 ASP.NET 5.0,我不知道如何编写 config.json 文件来执行相同的操作。

我已经尝试过

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

但它不起作用。关于如何将 web.config 部分直接映射到 config.json 以免破坏采用 web.config 的其他库,有什么建议吗?

该应用程序在本地 IIS Express 下运行,并且是 Azure 上的 Web 应用程序。

非常感谢!

最佳答案

您可以在 ASP.NET 5.0 中以不同的方式完成此任务。我在这个例子中使用了 json 文件。如果您需要添加 xml 文件,只需使用这些包 Microsoft.Framework.Configuration.Xml并使用.AddXmlFile()方法

This example uses beta 7

创建AppSetting类

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

    public string Setting2 { get; set; }

}

在启动文件中添加 json 文件,本示例中的配置为 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; }

然后您需要将应用程序服务添加到您的 AppSetting 类中,以便可以注入(inject)它 供以后使用

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

然后在你的 Controller 或任何你需要配置的地方注入(inject) IOptions<AppSettings>

public class SampleController : Controller
{

    private readonly AppSettings _appSettings;

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

}

这就是 json 的样子

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

我从 live.asp.net 获取了这些代码在github中

关于entity-framework-6 - ASP.NET 5 中的强类型 AppSettings 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33142052/

相关文章:

asp.net-core - 检测到的包版本超出依赖性约束 :Microsoft. AspNetCore.App 2.1.1

entity-framework - Studio 2015是否包括.edmx支持?

asynchronous - .net core 中的异步流下载

asp.net-core - NSwag AspNetCore 驼峰式生成设置

javascript - 将按钮的值传递给隐藏字段并将其保存到数据库

asp.net-core - Asp.net Core 中的 Web 应用程序与 Web Api 项目类型

asp.net-core - ASP.NET Identity 和 IdentityServer 有什么区别?

c# - 添加 ViewModel 类将代码优先模型添加到数据库

c# - EntityFramework 6 RC1 包含在多对多属性上失败

entity-framework - 将列名称约定添加到 EF6 FluentAPI