jky*_*dav 7 c# console-application entity-framework-6 asp.net-core
我正在尝试在我的控制台应用程序上阅读appsetting以及设置他的EntityFramework连接字符串.
我做了很多谷歌,但没有找到任何单一的解决方案,甚至没有在微软的文档.
这是我的问题.
Run Code Online (Sandbox Code Playgroud)string connectionString = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext<MyDBContext>(option =>option.UseSqlServer(connectionString, m => m.MigrationsAssembly("MyMVCDLL"))); services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
有人可以帮我弄这个吗.
首先,不要将敏感数据(登录名,密码,API密钥)保存在其中appsettings.json
,因为您可能会意外地将其提交给Verison Control,从而冒着您的凭据泄露的风险.为此,您必须使用User Secrets工具进行开发,有关详细信息,请参阅User Secret文档.
其次,阅读Configuration.GetConnectionString("DefaultConnection");
方法的工具提示文档.它明确指出`GetConnectionString是一个
GetSection的简写("ConnectionStrings")[name]
话虽这么说,你的appsettings.json必须如下所示:
{
...,
"ConnectionStrings":
{
"DefaultConnection" : "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;"
}
}
Run Code Online (Sandbox Code Playgroud)
或使用用户机密时:
dotnet user-secrets set ConnectionStrings:DefaultConnection Server = myServerAddress; Database = myDataBase; Trusted_Connection = True;
在控制台应用程序中使用它是完全相同的.配置包不是特定于ASP.NET Core的,可以单独使用.
所需的包是(取决于您要使用哪些包
"Microsoft.Extensions.Configuration":"1.0.0","Microsoft.Extensions.Configuration.EnvironmentVariables":"1.0.0","Microsoft.Extensions.Configuration.FileExtensions":"1.0.0","Microsoft.Extensions .Configuration.Json":"1.0.0","Microsoft.Extensions.Configuration.UserSecrets":"1.0.0",
构建配置的代码与ASP.NET Core中的代码完全相同.只是不是在Startup.cs
你的Main
方法中做到这一点:
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
// You can't use environment specific configuration files like this
// becuase IHostingEnvironment is an ASP.NET Core specific interface
//.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddUserSecrets()
.AddEnvironmentVariables();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8207 次 |
最近记录: |