使用 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/