如何在.NET Core中读取连接字符串?

175

我想从配置文件中仅读取一个连接字符串,为此需要向我的项目添加一个名为“appsettings.json”的文件,并将其内容添加到其中:

{
"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-

 WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
    "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Debug",
    "System": "Information",
    "Microsoft": "Information"
   }
 }
}

在ASP.NET上,我使用了这个:

 var temp=ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

现在我该如何在C#中读取“DefaultConnection”并将其存储在.NET Core的字符串变量中?


1
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration - Ravi Teja
6
这太搞笑了。这个问题应该很简单,但我看到的却是一堆答案,每个都走向不同的方向。 我本以为到了2022~2023年,事情应该变得简单了!我来到这里寻找答案,结果和来时一样,一无所获 :) 谢谢微软。 - undefined
4
这太搞笑了。那个问题应该很简单,但我看到的只有大量答案,每个都分叉成不同的方向。 我以为到了2022~2023年,事情应该变得简单了!我来到这里寻找答案,却像来时一样空手而归 :) 谢谢微软。 - Albert Zakhia
15个回答

1

虽然有些晚了,但在阅读了所有有用的答案和评论后,我最终使用了Microsoft.Extensions.Configuration.Binder扩展包,并做了一些调整来摆脱硬编码的配置键。

我的解决方案:

IConfigSection.cs

public interface IConfigSection
{
}

ConfigurationExtensions.cs

public static class ConfigurationExtensions
{
    public static TConfigSection GetConfigSection<TConfigSection>(this IConfiguration configuration) where TConfigSection : IConfigSection, new()
    {
        var instance = new TConfigSection();
        var typeName = typeof(TConfigSection).Name;
        configuration.GetSection(typeName).Bind(instance);

        return instance;
    }
}

appsettings.json

{
   "AppConfigSection": {
      "IsLocal": true
   },
   "ConnectionStringsConfigSection": {
      "ServerConnectionString":"Server=.;Database=MyDb;Trusted_Connection=True;",
      "LocalConnectionString":"Data Source=MyDb.db",
   },
}

要访问强类型配置,您只需要创建一个类来实现接口(注意:类名和字段名应与中的部分完全匹配)。

AppConfigSection.cs

public class AppConfigSection: IConfigSection
{
    public bool IsLocal { get; set; }
}

ConnectionStringsConfigSection.cs

public class ConnectionStringsConfigSection : IConfigSection
{
    public string ServerConnectionString { get; set; }
    public string LocalConnectionString { get; set; }

    public ConnectionStringsConfigSection()
    {
        // set default values to avoid null reference if
        // section is not present in appsettings.json
        ServerConnectionString = string.Empty;
        LocalConnectionString = string.Empty;
    }
}

最后,一个使用示例:

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        // some stuff

        var app = Configuration.GetConfigSection<AppConfigSection>();
        var connectionStrings = Configuration.GetConfigSection<ConnectionStringsConfigSection>();

        services.AddDbContext<AppDbContext>(options =>
        {
            if (app.IsLocal)
            {
                options.UseSqlite(connectionStrings.LocalConnectionString);
            }
            else
            {
                options.UseSqlServer(connectionStrings.ServerConnectionString);
            }
        });

        // other stuff
    }
}

为了使代码整洁,您可以将上述代码移入扩展方法中。
就这样,没有硬编码的配置键。

1

这个答案与其他答案类似,但更加直接。
在.NET Core 6中测试。
假设appsettings.json中的连接字符串如下。

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\xxx"
    "Connect_2": "Data Source=((SERVICE_NAMEXXX"
}

var builder = new ConfigurationBuilder();

builder.AddJsonFile("appsettings.json");

IConfiguration configuration = builder.Build();
string _connstr = configuration.GetConnectionString("DefaultConnection");
string _connstr2 = configuration.GetConnectionString("Connect_2");`

_connstr将保存"Server=(localdb)\xxx"。
_connstr2将保存"Data Source=((SERVICE_NAMEXXX"。


我认为这是在.Net Core中读取配置文件的简单直接的方法。在https://code-maze.com/dotnet-read-connection-strings/上列出并解释了许多不同的选项,包括使用ConfigurationBuilder()类。 - undefined

0
private readonly IConfiguration configuration;
        public DepartmentController(IConfiguration _configuration)
        {
            configuration = _configuration;
        }

        [HttpGet]
        public JsonResult Get()
        {
string sqlDataSource = configuration["ConnectionStrings:DefaultConnection"];

-1
我有一个数据访问库,可以与 .NET Core 和 .NET Framework 一起使用。
在 .NET Core 项目中的诀窍是将连接字符串保存在名为 "app.config" 的 XML 文件中(也适用于 Web 项目),并将其标记为“复制到输出目录”。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="conn1" connectionString="...." providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

ConfigurationManager.ConnectionStrings - 会读取连接字符串。

    var conn1 = ConfigurationManager.ConnectionStrings["conn1"].ConnectionString;

1
如果您正在使用.NET Core,最好采用其配置模式,而不是强行使用.NET Framework模式。 - Simmetric


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