0

I am trying to get data from database using ASP.NET CORE API the problem that I can't convert the datatable to JSON I used this solution but i got the same problem.

This is what I get every time I test with Postman

"[{\"id_auxiliaire\":\"0000000008522450131\",\"identite_fiscal_cin\":\"0XDERTTOL45\",\"NOM_RAISON_SOCIALE\":\"HIGHTech\",\"CodePostale\":41225,\"Ville\":\"USA\"},}]"

This is my WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

        // Web API configuration and services

        // Web API routes

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }

        );
        // Configure Web API to return JSON
        config.Formatters.JsonFormatter
        .SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));

    }
}

And this is my code

SqlDataAdapter da = new SqlDataAdapter($"select * from [UserDetail]   WHERE CONVERT(date, dateOperation) BETWEEN '{dd}' AND '{df}' ", con);
  
DataTable dt = new DataTable();
da.Fill(dt);

if (dt.Rows.Count > 0)
{
    string res = JsonConvert.SerializeObject(dt, Formatting.None);
    return new string[] { res };
}
haldo
  • 14,512
  • 5
  • 46
  • 52
S.Taha
  • 1
  • 2
    You will have to create/use a model object that has the structure you require. DataTables aren't what you need here. – phuzi Dec 21 '21 at 12:45
  • 2
    Also, you should use paramterised queries, otherwise you leave yourself open to SQL Injecxtion attacks. – phuzi Dec 21 '21 at 12:46
  • Your best bet is probably to update your data access technology, keeping in step with all of the other updated technologies you're using. (ADO.NET is *ancient*.) Take a look at some getting started tutorials/examples for using Entity Framework in your .NET Core project. – David Dec 21 '21 at 12:50
  • Thanks for reply @David i followed what you said and and it worked for me – S.Taha Dec 22 '21 at 10:25

0 Answers0