在ASP.NET Core控制台应用程序中读取appsettings

8

我正在尝试读取控制台应用程序的appsetting,并设置EntityFramework连接字符串。

我进行了大量的谷歌搜索,但没有找到任何单一的解决方案,甚至在微软的文档中也没有找到。

以下是我的问题。

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

有人可以帮我吗。

1个回答

8
首先,不要在 appsettings.json 中保存敏感数据(登录名、密码、API密钥),因为你可能会意外提交到版本控制,从而导致凭证泄露。为此,你需要使用开发过程中的用户秘密工具,请参阅用户秘密文档获取详细信息。
其次,请仔细阅读 Configuration.GetConnectionString("DefaultConnection"); 方法的工具提示文档。它明确指出 `GetConnectionString 是一个

缩写 GetSection(“ConnectionStrings”)[name]

话虽如此,你的 appsettings.json 必须像这样:
{
    ...,
    "ConnectionStrings":
    {
        "DefaultConnection" : "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;"
    }
}

或者当使用用户机密时:

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中的完全相同。只需将其放在Main方法中而不是在Startup.cs中即可:

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();

1
我完全理解问题中提到的内容,我在MVC应用程序中使用相同的内容,但我的问题是如何在控制台应用程序中访问它,如果可能的话最好分享一些代码。我需要知道要使用哪个构建器类和哪个dll。 - jkyadav
完全一样。配置包不是特定于ASP.NET Core的,因为它驻留在“Microsoft.Extensions.Configuration”包中。 - Tseng
好的,我将如何使用以下代码:string connectionString = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext(option =>option.UseSqlServer(connectionString, m => m.MigrationsAssembly("MyMVCDLL"))); services.Configure(Configuration.GetSection("AppSettings"));将其翻译为中文: - jkyadav
我完全不知道这里的情况。在MVC应用程序中,我使用依赖注入获取appsetting,如下所示:“IOptions<AppSettings> appSettings”。 - jkyadav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接