阅读asp net core console应用程序中的appsettings

jky*_*dav 7 c# console-application entity-framework-6 asp.net-core

我正在尝试在我的控制台应用程序上阅读appsetting以及设置他的EntityFramework连接字符串.

我做了很多谷歌,但没有找到任何单一的解决方案,甚至没有在微软的文档.

这是我的问题.

  1. 如何设置EntityFramework连接字符串?,我的实体框架项目是独立的,对于我的MVC项目我做了如下代码.
string connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<MyDBContext>(option =>option.UseSqlServer(connectionString, m => m.MigrationsAssembly("MyMVCDLL")));
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
Run Code Online (Sandbox Code Playgroud)
  1. 如何阅读appsetting?
  2. 如何在控制台应用程序中实现DI以获取appsettings?

有人可以帮我弄这个吗.

Tse*_*eng 8

首先,不要将敏感数据(登录名,密码,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)