返回格式为JSon格式的接口:
1. 在Web.config 文件中配置一个全局的数据库链接字符串
在
<configuration>...</configuration>
中 添加以下代码
<appSettings>
<add key="ConnectionString" value="Database='test';Data Source=localhost;User ID=root;Password=;CharSet=utf8"/>
</appSettings>
2. 在 WebApiConfig.cs 中设置为返还格式为JSon格式
// Web API 配置和服务
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Formatters.Add(config.Formatters.JsonFormatter);
3. 添加MySQL 引用
4. 创建一个Model类(Buyer.cs)
public class Buyer
{
public string name { set; get; }
public string password { get; set; }
}
5. 在controller 中使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MySql.Data;
using MySql.Data.MySqlClient;
using WebApiDemo.Models;
using System.Data;
namespace WebApiDemo.Controllers
{
public class ApiTestController : ApiController
{
//List<Buyer> buyers = new List<Buyer>
// {
// new Buyer {name= "小韩",password="fdfdf122"},
// };
string strConn = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString();
//public IHttpActionResult GetRoule()
//{
// return Json(new { msg=strConn } );
//}
[HttpGet]
public List<Models.Buyer> getMySQLHandel()
{
string queryString = "SELECT * FROM buyer";
List<Models.Buyer> list = new List<Models.Buyer>();
using (MySqlConnection connection = new MySqlConnection(strConn)) //连接数据库
{
MySqlCommand command = new MySqlCommand(queryString, connection);
connection.Open();
DataSet ds = new DataSet();
MySqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
Models.Buyer model = new Models.Buyer();
object obj;
obj = dr["name"];
if (obj != null && obj != DBNull.Value)
{
model.name = (string)obj;
}
model.name = dr["name"].ToString();
model.password = dr["password"].ToString();
list.Add(model);
}
}
return list;
}
}
}