[英]How to access Azure SQL database with a Connection String in C#?
[英]How to access Azure SQL Connection string from project Service Dependencies
我在 MS Visual Studio(ASP.NET Core Web 应用程序)中启动了 Azure REST API 的新项目,我想使用项目服务依赖项来管理与 Azure SQL 数据库的连接。 所以 - 我创建了依赖项,设置了 conn.string 的名称,设置了连接属性,一切看起来都很好......但是现在我找不到如何在代码中读取(获取)这个连接字符串。 像这样的东西:
private SqlConnection sqlConnection;
private DataConnector()
{
string connectionString = GET_CONSTR_FROM_DEPENDENCY([NameOfMyConnStr]);
sqlConnection = new SqlConnection(connectionString);
}
我发现了一些关于依赖注入的内容,但我不确定这是正确的......你能帮忙吗?
依赖于 IConfiguration 服务。
例如
public class TestModel : PageModel
{
// requires using Microsoft.Extensions.Configuration;
private readonly IConfiguration Configuration;
public TestModel(IConfiguration configuration)
{
Configuration = configuration;
}
public ContentResult OnGet()
{
var myKeyValue = Configuration["MyKey"];
var title = Configuration["Position:Title"];
var name = Configuration["Position:Name"];
var defaultLogLevel = Configuration["Logging:LogLevel:Default"];
return Content($"MyKey value: {myKeyValue} \n" +
$"Title: {title} \n" +
$"Name: {name} \n" +
$"Default Log Level: {defaultLogLevel}");
}
}
或者在你的情况下
class DataConnector
{
private SqlConnection sqlConnection;
private DataConnector(IConfiguration config)
{
string connectionString = config.GetConnectionString(NameOfMyConnString);
sqlConnection = new SqlConnection(connectionString);
}
}
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.