获取控制器中的连接字符串? [重复]

问题描述 投票:-3回答:2

appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=....;User ID=...;Password=....."

Startup.cs:

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

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<SyncOptions>(Configuration.GetSection("App"));
    services.AddDbContext<SinsoContext>(o => o.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddMvc();
}

如何在Controller或Service类中获取连接字符串?我尝试了以下代码,但它删除了密码。

var connStr = _context.Database.GetDbConnection().ConnectionString;
c# asp.net-core entity-framework-core
2个回答
2
投票

您可以使用强类型配置。创建一个类,如:

public class ConnectionStringsConfig
{
    public string DefaultConnection { get; set; }
}

然后,将其添加到您的服务:

services.Configure<ConnectionStringsConfig>(Configuration.GetSection("ConnectionStrings"));

然后,在你的控制器中,注入IOptionsSnapshot<ConnectionStringsConfig>

public class FooController : Controller
{
    private ConnectionStringsConfig _connectionStrings;

    public FooController(IOptionsSnapshot<ConnectionStringsConfig> connectionStrings)
    {
        _connectionStrings = connectionStrings?.Value ?? throw new ArgumentNullException(nameof(connectionStrings));
    }
}

最后,只需使用_connectionStrings.DefaultConnection,您需要它。

也就是说,我同意其他人认为这是一种代码味道。控制器不需要连接字符串。任何需要访问连接字符串的东西都应该存在于控制器之外的某个地方。但是,您可以使用相同的方法将连接字符串注入到该帮助程序/服务类中,然后将该帮助程序/服务类注入到控制器中。


-1
投票

尝试设置Persist Security Info=True示例:

connectionString="Persist Security Info=True;Data Source=MyDataSource;Initial Catalog=MyDatabase;user id=myUserId;password=pass"
© www.soinside.com 2019 - 2024. All rights reserved.