Search code examples
c#.netado.net

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


I write my connection string like that:

{
  "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": "*"

When I want to navigate in the url address I receive error:

SocketException: No such host is known.

and the debugger stuck at this method:

[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);
}

at this line:

mycon.Open();

What do I need to do to properly load my database?


Solution

  • You can separate Data Source and Port values as mentioned above, also ',' instead of ':' delimiter should work fine ("Data Source=192.168.1.24,3306;")