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

mot*_*deh 87 c# connection-string asp.net-core-1.0

我想从配置文件中只读取一个连接字符串,并为此添加一个名为"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"
   }
 }
}
Run Code Online (Sandbox Code Playgroud)

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

 var temp=ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
Run Code Online (Sandbox Code Playgroud)

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

Bra*_*ton 89

发布的答案很好,但没有直接回答我在连接字符串中读取的相同问题.通过大量搜索,我发现了一种稍微简单的方法.

在Startup.cs中

public void ConfigureServices(IServiceCollection services)
{
    ...
    // Add the whole configuration object here.
    services.AddSingleton<IConfiguration>(Configuration);
}
Run Code Online (Sandbox Code Playgroud)

在控制器中,在构造函数中为配置添加一个字段并为其添加一个参数

private readonly IConfiguration configuration;

public HomeController(IConfiguration config) 
{
    configuration = config;
}
Run Code Online (Sandbox Code Playgroud)

现在稍后在您的视图代码中,您可以访问它:

connectionString = configuration.GetConnectionString("DefaultConnection");
Run Code Online (Sandbox Code Playgroud)

  • 我同意@JustJohn 的观点,这是最好的不必要的过度设计。连接字符串应该很容易获得,并且不应该花费几个小时来实现。没有必要把一切都抽象化并包装在工厂里,天知道还有什么。有些事情应该始终保持简单。 (9认同)
  • 是的 太多的计算机科学家仅仅为了说“ Hello World”而创造了巨大的成就。难以置信的。最好的是熵。 (4认同)
  • @Jon Story:哦,应该吗?首先,出于安全原因,在不需要的情况下,不应以任何方式访问连接字符串等机密信息。其次,如果您绝对愿意,您可以通过 DI 使其全局可用,或者您自己将其放入静态变量/属性中,框架不会为您执行此操作。第三,您应该创建为数据访问而传递的服务(例如连接工厂),而不是传递连接字符串。仅当您在启动时配置服务时才需要连接字符串。 (3认同)
  • 不会那样做。如果没有实体框架,则最好将连接工厂注册为单例,例如与dapper一起使用。然后,您仍然可以根据需要公开一个connectionString属性,但是我敢打赌,在99%的情况下都没有必要。 (2认同)
  • 但是,如何访问模型而不是控制器中的配置? (2认同)
  • 我阅读和尝试的内容越多,我就越意识到获得连接字符串是一项主要任务。无论我尝试什么,我都会得到null。 (2认同)
  • @JustJohn:我理解你的不满,但是正确的设计是可测试的,这意味着你必须在构造函数中传递依赖项,否则你的应用程序/框架不可进行单元测试。这也是正确的设计,因为您可以将一个组件替换为另一个组件,而无需更改大量代码。如果你不想传递 100 个参数,你也可以将 System.IServiceProvider 传递到类中,然后你可以在那里获取依赖项。但硬币的另一面是,这会增加复杂性。 (2认同)

Ste*_*ger 78

您可以使用GetConnectionString扩展方法执行此操作:

string conString = Microsoft
   .Extensions
   .Configuration
   .ConfigurationExtensions
   .GetConnectionString(this.Configuration, "DefaultConnection");

System.Console.WriteLine(conString);
Run Code Online (Sandbox Code Playgroud)

或者使用DI的结构化类:

public class SmtpConfig
{
    public string Server { get; set; }
    public string User { get; set; }
    public string Pass { get; set; }
    public int Port { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

启动:

public IConfigurationRoot Configuration { get; }


// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // http://developer.telerik.com/featured/new-configuration-model-asp-net-core/
    // services.Configure<SmtpConfig>(Configuration.GetSection("Smtp"));
    Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure<SmtpConfig>(services, Configuration.GetSection("Smtp"));
Run Code Online (Sandbox Code Playgroud)

然后在家庭控制器:

public class HomeController : Controller
{

    public SmtpConfig SmtpConfig { get; }
    public HomeController(Microsoft.Extensions.Options.IOptions<SmtpConfig> smtpConfig)
    {
        SmtpConfig = smtpConfig.Value;
    } //Action Controller


    public IActionResult Index()
    {
        System.Console.WriteLine(SmtpConfig);
        return View();
    }
Run Code Online (Sandbox Code Playgroud)

在appsettings.json中使用它:

"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},

"Smtp": {
    "Server": "0.0.0.1",
    "User": "user@company.com",
    "Pass": "123456789",
    "Port": "25"
  }
Run Code Online (Sandbox Code Playgroud)

  • `Configure`是一种扩展方法.最常用的应该是这样的:`services.Configure <SmtpConfig>(Configuration.GetSection("Smtp"));`当然,这是一回事,但我认为人们不会意识到只会开始做"错误" "方式,使用未注释的行,所以最好删除该行.;) (8认同)
  • 连接字符串部分中的“this.Configuration”指的是什么?GetConnectionString(this.Configuration, "DefaultConnection") (5认同)
  • @JedatKinports:不,只有注射。即使您要编写静态方法,您仍然需要配置。不过,您可以手动读取 JSON/YAML 文件。但这将消除覆盖,例如用户机密或其他(例如,来自注册表的配置)。 (4认同)
  • 我收到一条错误消息:“MyClass 确实包含了‘配置’的定义……” (2认同)

小智 25

在 .NET Core 6 中

应用程序设置.json

 "ConnectionStrings": {
   "DefaultConnection": "Server=**Server Name**;Database=**DB NAME**;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
Run Code Online (Sandbox Code Playgroud)

程序.cs

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));
Run Code Online (Sandbox Code Playgroud)

数据库上下文

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {

    }

}
Run Code Online (Sandbox Code Playgroud)


小智 14

我就是这样做的:

我在 appsettings.json 添加了连接字符串

"ConnectionStrings": {
"conStr": "Server=MYSERVER;Database=MYDB;Trusted_Connection=True;MultipleActiveResultSets=true"},
Run Code Online (Sandbox Code Playgroud)

我创建了一个名为 SqlHelper 的类

public class SqlHelper
{
    //this field gets initialized at Startup.cs
    public static string conStr;

    public static SqlConnection GetConnection()
    {
        try
        {
            SqlConnection connection = new SqlConnection(conStr);
            return connection;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在 Startup.cs 中,我使用 ConfigurationExtensions.GetConnectionString 来获取连接,并将其分配给 SqlHelper.conStr

public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        SqlHelper.connectionString = ConfigurationExtensions.GetConnectionString(this.Configuration, "conStr");
    }
Run Code Online (Sandbox Code Playgroud)

现在,无论您需要连接字符串,您都可以这样调用它:

SqlHelper.GetConnection();
Run Code Online (Sandbox Code Playgroud)


mar*_*ate 13

有关详细信息,请参阅链接:https: //docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings

JSON

    {
      "ConnectionStrings": {
        "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
      },
    }
Run Code Online (Sandbox Code Playgroud)

C#Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*ite 6

我发现解决此问题的方法是在启动时在构建器中使用AddJsonFile(这使它可以找到存储在appsettings.json文件中的配置),然后使用它来设置私有_config变量

public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        _config = builder.Build();
    }
Run Code Online (Sandbox Code Playgroud)

然后我可以将配置字符串设置如下:

var connectionString = _config.GetConnectionString("DbContextSettings:ConnectionString"); 
Run Code Online (Sandbox Code Playgroud)

这是在dotnet core 1.1上

  • 如何在控件中访问_config? (4认同)

小智 5

ASP.NET Core在我的例子中是3.1)为我们提供了到 Controllers 的构造函数注入,所以你可以简单地添加以下构造函数:

[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
    private readonly IConfiguration m_config;

    public TestController(IConfiguration config)
    {
        m_config = config;
    }

    [HttpGet]
    public string Get()
    {
        //you can get connection string as follows
        string connectionString = m_config.GetConnectionString("Default")
    }
}
Run Code Online (Sandbox Code Playgroud)

appsettings.json 可能如下所示:

{
    "ConnectionStrings": {
        "Default": "YOUR_CONNECTION_STRING"
        }
}
Run Code Online (Sandbox Code Playgroud)