一、新建项目
1、控制器新建
2、Service层新建
3、Business数据层新建
4、Commons公共层新建
5、Models实体层新建
二、调用接口
1、接口建立
Web API 2 控制器新建
2、调用
三、Swagger接口调试配置
1、添加NuGet包
在启动项中添加Swashbuckle NuGet包
2、访问
https://localhost:xxx/swagger
四、接口调用MySQL数据库查询
1、Business层
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MindERP.Business
{
public class TestBusiness
{
//添加用户
public erpa_user_tbl SelectUserById(int id)
{
string constr = "Server=xxx;UserId=xxx;Password=xxx;Database=xxx;pooling=false;CharSet=utf8;port=3306";
MySqlConnection conn = new MySqlConnection(constr);
try
{
conn.Open();
string mySql = "select * from erpa_user_tbl where id = @id";
MySqlCommand sqlcmd2 = new MySqlCommand(mySql, conn);
MySqlParameter p1 = new MySqlParameter("@id", MySqlDbType.Int32);
p1.Value = id;
sqlcmd2.Parameters.Add(p1);
erpa_user_tbl user = new erpa_user_tbl();
MySqlDataReader sqlreader = sqlcmd2.ExecuteReader();
while (sqlreader.Read())
{
user.id = Convert.ToInt32(sqlreader["id"]);
user.user_name = sqlreader["user_name"].ToString();
}
return user;
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
conn.Close();
conn.Dispose();
}
return new erpa_user_tbl();
}
public class erpa_user_tbl
{
public int id { get; set; }
public string user_name { get; set; }
}
}
}
2、Service层
using MindERP.Business;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static MindERP.Business.TestBusiness;
namespace MindERP.Service
{
public class TestService
{
public TestBusiness testBusiness;
public TestService()
{
testBusiness = new TestBusiness();
}
public erpa_user_tbl SelectUserById(int id)
{
return testBusiness.SelectUserById(id);
}
}
}
3、控制器入口
using MindERP.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace MindERP.API.Controllers
{
public class TestController : ApiController
{
public TestService testService;
public TestController()
{
testService = new TestService();
}
[HttpGet]
public IHttpActionResult Hello(int id)
{
var result = testService.SelectUserById(id);
return Json(result);
}
}
}
4、接口调用
注:能力有限,还请谅解,争取早日能够写出有质量的文章!
我是皮蛋布丁,一位爱吃皮蛋的热爱运动的废铁程序猿。