I am new when it comes to C# and .Net applications however im trying to build a Web API that pulls data from a MySql
database and displays it in JSON format when you reach that endpoint.
I am using MySql.Data.MySqlClient
for this and intend on using Newtonsoft.JSON
to serialise the result format in JSON formatting.
Code:
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
MySqlConnection conn = new MySqlConnection(@"server=localhost;port=3306;database=mysql;username=root;password=[PASSWORD];");
[HttpGet]
public string Get()
{
MySqlCommand query = conn.CreateCommand();
query.CommandText = "SELECT * FROM engine_cost LIMIT 100";
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
MySqlDataReader fetch_query = query.ExecuteReader();
while (fetch_query.Read())
{
return fetch_query.ToString(); // Result: "MySql.Data.MySqlClient.MySqlDataReader"
}
return "yay"; // Return JSON with Database values
}
}
I know the code is a bit messy but im really unsure on how to tackle this.
Thanks in advance