[英]While trying to read ConnectionString value in C# .net 6.0 console app getting Object reference null error
I have a console application(.Net 6.0) with app.config file with following data.我有一个带有 app.config 文件的控制台应用程序(.Net 6.0),其中包含以下数据。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name ="ConnectionKey" connectionString="my connection value" providerName="System.Data.SqlClient"/>
</connectionStrings>
I am trying to read the connection string the following way but I get the error "Object reference not set to an instance of an object."我试图通过以下方式读取连接字符串,但出现错误“对象引用未设置为 object 的实例”。
cnx = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionKey"].ConnectionString);
Is there something more I have to add?我还有什么要补充的吗? Or is there any other approach to read the connectionString value?还是有其他方法可以读取 connectionString 值?
Update:更新:
I have changed the app.config to appsettings.json with following code我已使用以下代码将 app.config 更改为 appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true",
"MyConn": "my connection string"
}
}
You can get the connection string like below:您可以获得如下连接字符串:
public class HomeController : Controller
{
public readonly IConfiguration _configuration;
public HomeController(IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult Index()
{
string conn = _configuration.GetConnectionString("MyConnection");
var cnx = new SqlConnection(conn);
//do your stuff...
return View();
}
}
appsettings.json: appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"MyConnection": "your connection string" //focus here...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.