在 .NET Core 上的 c# web API 中编写连接字符串如何正确?

How is correct to write connection string in c# web API on .NET Core?

我这样写我的连接字符串:

{
  "ConnectionStrings": {
    "AppCon": "Data Source=192.168.1.24:3306; Initial Catalog=dbName; User Id=UName; Password=Pass"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"

当我想在 url 地址中导航时,我收到错误消息:

SocketException: No such host is known.

调试器停留在这个方法上:

[HttpGet]
public JsonResult Get()
{
    string query = @"SELECT Station, Ime FROM auto_q_stations;";

    DataTable table = new DataTable();

    string sqlDataSource = _configuration.GetConnectionString("AppCon");

    MySqlDataReader myReader;

    using(MySqlConnection mycon = new MySqlConnection(sqlDataSource))
    {
        mycon.Open();
        using(MySqlCommand myCommand = new MySqlCommand(query, mycon))
        {
            myReader = myCommand.ExecuteReader();
            table.Load(myReader);

            myReader.Close();
            mycon.Close();
        }
    }
    return new JsonResult(table);
}

在这一行:

mycon.Open();

我需要做什么才能正确加载我的数据库?

从连接字符串中删除:3306; 3306 是默认值,因此您无需指定它。如果您确实要指定非标准端口,请输入例如 Data Source=192.168.1.24;Port=12345;Initial Catalog=..

您可以在以下位置查看可在连接字符串中使用的关键字的完整列表:https://dev.mysql.com/doc/dev/connector-net/6.10/html/P_MySql_Data_MySqlClient_MySqlConnection_ConnectionString.htm

您可以如上所述分隔数据源和端口值,用“,”代替“:”定界符应该可以正常工作(“数据源=192.168.1.24,3306;”)