Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net web api with Mysql database

I have a background in PHP and bump into a problem while trying out ASP.NET webAPI.

I have a MySQL database and a table that contains some files information. Now i want to make a "SELECT * FROM Files" and see the result in XML.

How can i render the result of the query that is returned?

This is my code at the moment,

The Model:

namespace ProductsApp.Models
{
    public class File
    {
        public int Id {get; set;}
        public string Text {get; set;}
    }
}

The Controller:

public IEnumerable<File> Get()
{
    try
    {
        command = conn.CreateCommand();
        command.CommandText = "SELECT * FROM Files";
        conn.Open();

        MySqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            //How to output the rows ????
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

    return null; // return the list
}
like image 914
Webbie Avatar asked Oct 30 '25 18:10

Webbie


1 Answers

Making some assumptions about your File Table, this is how you get the data

public IEnumerable<File> Get()
{
    List<File> list = new List<File>();
    try
    {
        command = conn.CreateCommand();
        command.CommandText = "SELECT * FROM Files";
        conn.Open();

        using(MySqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                //How to output the rows ????
                int id = (int) reader["Id"];//Assuming column name is 'Id' and value if typeof(int)
                string text = (string) reader["Text"];//Assuming column name is `Text` and typeof(string)
                var file = new File {Id = id, Text = text};
                list.Add(file);
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

    return list; // return the list
}

As for the xml that is a formatting setting that needs to be allowed on the request.

Given the default setup of WebApi once the client making the call requests text/xml as the content type then the result should be parsed to xml and returned to the client.

If it is you want to force the response to always be xml then you need to make some changes to the response. One way is to set the Content-Type header before returning your result.

Response.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml;charset=utf-8");

There are other ways you can do this and there are many answers on SO that will be able to show you.

like image 133
Nkosi Avatar answered Nov 02 '25 06:11

Nkosi