【问题标题】:asp.net web api with Mysql database带有 Mysql 数据库的 asp.net web api
【发布时间】:2016-03-23 19:56:35
【问题描述】:

我有 PHP 背景,在尝试 ASP.NET webAPI 时遇到了问题。

我有一个 MySQL 数据库和一个包含一些文件信息的表。 现在我想做一个“SELECT * FROM Files”并在 XML 中查看结果。

如何呈现返回的查询结果?

这是我目前的代码,

模特:

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

控制者:

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
}

【问题讨论】:

标签: c# mysql asp.net-web-api asp.net-web-api2


【解决方案1】:

对你的文件表做一些假设,这就是你获取数据的方式

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
}

至于 xml 是需要在请求中允许的格式设置。

一旦客户端发出调用请求text/xml作为内容类型,则给定WebApi的默认设置,则结果应解析为xml并返回给客户端。

如果您想强制响应始终为 xml,那么您需要对响应进行一些更改。一种方法是在返回结果之前设置 Content-Type 标头。

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

还有其他方法可以做到这一点,并且有很多关于 SO 的答案可以告诉你。

【讨论】:

  • 谢谢!我得到 en 例外 403 被禁止。我需要在 web.config 中提供 i 连接字符串来解决这个 403 问题吗?
  • 状态码 403:如果您在 api 的全局控制器上为您的服务启用了身份验证,则会发生禁止。检查控制器上的 [Authorize] 属性。如果您想允许非授权用户执行特定操作,您可以在操作上使用[AllowAnonymous] 属性
  • 我已将 [AllowAnonymous] 设置为我的方法和 Controller 类,我得到:ex.Message = "无法连接到任何指定的 MySQL 主机。"
  • 检查您的连接字符串并确保它是正确的。这通常是该消息的含义。
【解决方案2】:

网络配置:

     public static MySqlConnection conn()
    {
        string conn_string = "server=localhost;port=3306;database=testmvc;username=root;password=root;";


        MySqlConnection conn = new MySqlConnection(conn_string);

        return conn;
    }

控制器:

    public MySqlConnection con = WebApiConfig.conn();

    public IHttpActionResult GetAllProduct()
    {
        IList<product> pro = null;

        try
        {
            con.Open();
            MySqlCommand cmd = new MySqlCommand("select * from product", con);

            cmd.CommandType = CommandType.Text;

            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

            pro = ds.Tables[0].AsEnumerable().Select(dataRow => new product { Pname = dataRow.Field<string>("pname"), Pid = dataRow.Field<int>("pid"), Pprice = dataRow.Field<decimal>("pprice") }).ToList();

        }
        finally
        {
            con.Close();
        }


        if (pro.Count == 0)
        {
            return NotFound();
        }

        return Ok(pro);
    }

    public IHttpActionResult PostNewProduct(product pro)
    {
        try
        {
            con.Open();

            MySqlCommand cmd = new MySqlCommand();

            cmd.Connection = con;
            cmd.CommandText = "SELECT MAX(pid) from product";

            cmd.CommandType = CommandType.Text;

            int maxid = Convert.ToInt16(cmd.ExecuteScalar().ToString())+1;


            cmd.CommandText = "insert into product values(" + maxid + ",'" + pro.Pname + "'," + pro.Pprice + ")";

            cmd.ExecuteNonQuery();

        }
        finally
        {
            con.Close();
        }

        return Ok();
    }

    public IHttpActionResult PutOldProduct(product pro)
    {

        string sql = "update product set pname='" + pro.Pname + "',pprice=" + pro.Pprice + " where pid=" + pro.Pid + "";
        try
        {
            con.Open();
            MySqlCommand cmd = new MySqlCommand(sql, con);

            cmd.CommandType = CommandType.Text;

            cmd.ExecuteNonQuery();

        }
        finally
        {
            con.Close();
        }

        return Ok();
    }

    public IHttpActionResult Delete(int id)
    {
        string sql = "delete from product where pid=" + id + "";
        try
        {
            con.Open();
            MySqlCommand cmd = new MySqlCommand(sql, con);

            cmd.CommandType = CommandType.Text;

            cmd.ExecuteNonQuery();

        }
        finally
        {
            con.Close();
        }

        return Ok();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-20
    • 2015-04-03
    • 2013-09-24
    • 2012-07-23
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多