作者:xcLeigh
文章地址:https://blog.csdn.net/weixin_43151418/article/details/131458922
asp.net core 框架搭建2-搭建webapi
,本文章介绍asp.net core webapi框架搭建,然后开发增删改查和工具接口,将一步步带着大家,实现目标。所有操作过程将展现在本篇文章,下面咋们一起来实现它吧。
第五步 运行项目(方式1:直接按F5;方式2:vs2022工具点三角启动,在浏览器中查看),查看效果
接口返回数据效果
简单的框架搭建起来了,下面咋们在里面开始操作数据了。
新建表sys_user
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`tel` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`addr` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 12 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
"ConnectionStrings": {
"MysqlConnection": "Data Source=IP地址;Database=数据库名称;User ID=用户名;Password=密码;port=端口;sslmode=none;CharSet=utf8;pooling=true;"
},
program.cs中注入数据库连接串
//Transient:每次从容器 (IServiceProvider)中获取的时候都是一个新的实例
//Singleton:每次从同根容器中(同根IServiceProvider)获取的时候都是同一个实例
//Scoped:每次从同一个容器中获取的实例是相同的
builder.Services.AddTransient(_ => new AppDb(builder.Configuration.GetConnectionString("MysqlConnection")));
从配置文件读取ConnectionString,创建连接对象。
public class AppDb : IDisposable
{
public MySqlConnection Connection;
public AppDb(string connectionString)
{
Connection = new MySqlConnection(connectionString);
}
public void Dispose()
{
Connection.Close();
}
}
引用数据库实体类
public class UserInfoModel
{
[JsonIgnore]
public AppDb Db { get; set; }
public UserInfoModel(AppDb db = null)
{
Db = db;
}
public int Id { get; set; }
public string UserName { get; set; }
public string PassWord { get; set; }
public string Tel { get; set; }
public string Email { get; set; }
public string Addr { get; set; }
}
普通参数实体类
public class UserInfo
{
public int Id { get; set; }
public string UserName { get; set; }
public string PassWord { get; set; }
public string Tel { get; set; }
public string Email { get; set; }
public string Addr { get; set; }
}
这里面集中了对数据库的增上改查,分页,根据条件查询等方法,可以直接调用。
//操作数据库
public class AppDbOper
{
public readonly AppDb Db;
public AppDbOper(AppDb db)
{
Db = db;
}
#region 新增修改
public async Task InsertAsync(UserInfo userInfo)
{
var cmd = Db.Connection.CreateCommand() as MySqlCommand;
cmd.CommandText = @"INSERT INTO `sys_user` (`username`,`password`,`tel`,`email`,`addr`)VALUES(@username,@password,@tel,@email,@addr);";
BindParams(cmd, userInfo);
int num=await cmd.ExecuteNonQueryAsync();
int id = (int)cmd.LastInsertedId;
return num;
}
public async Task UpdateAsync(UserInfo userInfo)
{
var cmd = Db.Connection.CreateCommand() as MySqlCommand;
cmd.CommandText = @"UPDATE `sys_user` SET `username`=@username,`password`=@password,`tel`=@tel,`email`=@email,`addr`=@addr WHERE `Id`=@id;";
BindParams(cmd, userInfo);
BindId(cmd, userInfo.Id);
int num = await cmd.ExecuteNonQueryAsync();
return num;
}
private void BindId(MySqlCommand cmd,int id)
{
cmd.Parameters.Add(new MySqlParameter
{
ParameterName = "@id",
DbType = DbType.Int32,
Value = id,
});
}
private void BindParams(MySqlCommand cmd,UserInfo userInfo)
{
cmd.Parameters.Add(new MySqlParameter
{
ParameterName = "@password",
DbType = DbType.String,
Value = userInfo.PassWord,
});
cmd.Parameters.Add(new MySqlParameter
{
ParameterName = "@username",
DbType = DbType.String,
Value = userInfo.UserName,
});
cmd.Parameters.Add(new MySqlParameter
{
ParameterName = "@tel",
DbType = DbType.String,
Value = userInfo.Tel,
});
cmd.Parameters.Add(new MySqlParameter
{
ParameterName = "@email",
DbType = DbType.String,
Value = userInfo.Email,
});
cmd.Parameters.Add(new MySqlParameter
{
ParameterName = "@addr",
DbType = DbType.String,
Value = userInfo.Addr,
});
}
#endregion
#region 删除
public async Task DeleteAllAsync(string id)
{
//var txn = await Db.Connection.BeginTransactionAsync();
int num = 0;
try
{
var cmd = Db.Connection.CreateCommand() as MySqlCommand;
cmd.CommandText = @"DELETE FROM `sys_user` where id=@id";
cmd.Parameters.Add(new MySqlParameter
{
ParameterName = "@id",
DbType = DbType.Int32,
Value = id,
});
num =await cmd.ExecuteNonQueryAsync();
//await txn.CommitAsync();
}
catch
{
//await txn.RollbackAsync();
//throw;
}
return num;
}
#endregion
public async Task FindOneAsync(int id)
{
var cmd = Db.Connection.CreateCommand() as MySqlCommand;
cmd.CommandText = @"SELECT `Id`, `username`, `password`, `tel`, `email`, `addr` FROM `sys_user` WHERE `Id` = @id";
cmd.Parameters.Add(new MySqlParameter{
ParameterName = "@id",
DbType = DbType.Int32,
Value = id,
});
var result = await ReadAllAsync(await cmd.ExecuteReaderAsync());
return result.Count > 0 ? result[0] : null;
}
#region 分页
public async Task getListCount(string username) {
int num = 0;
var cmd = Db.Connection.CreateCommand();
cmd.CommandText = @"select count(*) num from `sys_user` where username like @username";
cmd.Parameters.Add(new MySqlParameter
{
ParameterName = "@username",
DbType = DbType.String,
Value = "%" + username + "%",
});
var reader = await cmd.ExecuteReaderAsync();
while (reader.Read())
{
if (!reader.IsDBNull(reader.GetOrdinal("num")))
{
num = Convert.ToInt32(reader[0]);
}
else
{
num = 0;
}
}
return num;
}
public async Task> ListPostsAsync(int page, int limit, string username)
{
//limit 页大小 page 第几页
int _startPage = limit * (page-1);
int _endPage = limit * (page-1)+limit;
var cmd = Db.Connection.CreateCommand();
cmd.CommandText = @"SELECT `Id`, `username`, `password`, `tel`, `email`, `addr` FROM `sys_user` where username like @username ORDER BY `Id` DESC LIMIT @start,@end;";
cmd.Parameters.Add(new MySqlParameter
{
ParameterName = "@username",
DbType = DbType.String,
Value = "%"+username+"%",
});
cmd.Parameters.Add(new MySqlParameter
{
ParameterName = "@start",
DbType = DbType.Int32,
Value = _startPage,
});
cmd.Parameters.Add(new MySqlParameter
{
ParameterName = "@end",
DbType = DbType.Int32,
Value = _endPage,
});
return await ReadAllAsync(await cmd.ExecuteReaderAsync());
}
#endregion
public async Task> LatestPostsAsync()
{
var cmd = Db.Connection.CreateCommand();
cmd.CommandText = @"SELECT `Id`, `username`, `password`, `tel`, `email`, `addr` FROM `sys_user` ORDER BY `Id` DESC LIMIT 10;";
return await ReadAllAsync(await cmd.ExecuteReaderAsync());
}
private async Task> ReadAllAsync(DbDataReader reader)
{
var posts = new List();
using (reader)
{
while (await reader.ReadAsync())
{
var post = new UserInfoModel(Db)
{
Id = await reader.GetFieldValueAsync(0),
UserName = await reader.GetFieldValueAsync(1),
PassWord = await reader.GetFieldValueAsync(2),
Tel = await reader.GetFieldValueAsync(3),
Email = await reader.GetFieldValueAsync(4),
Addr = await reader.GetFieldValueAsync(5)
};
posts.Add(post);
}
}
return posts;
}
}
#region 根据id查询数据
[HttpGet]
public async Task> getUserInfoById(int id)
{
using (_db)
{
await _db.Connection.OpenAsync();
var query = new AppDbOper(_db);
var result = await query.FindOneAsync(id);
if (result == null)
return new ApiResponse(200, "暂无数据", null);
return new ApiResponse(200, "请求成功", result);
}
}
#endregion
#region 根据条件查询数据,分页
[HttpGet]
public async Task>> getUserInfoPage(int page, int limit, string? username)
{
using (_db)
{
await _db.Connection.OpenAsync();
var query = new AppDbOper(_db);
int num = await query.getListCount(username);
await _db.Connection.CloseAsync();
await _db.Connection.OpenAsync();
var result = await query.ListPostsAsync(page,limit,username);
if (result == null)
return new ApiResponse>(200, num+"", null);
return new ApiResponse>(200, num + "", result);
}
}
#endregion
#region 新增数据
[HttpGet]
public async Task addUserInfo([FromQuery] UserInfo userInfo)
{
using (_db)
{
await _db.Connection.OpenAsync();
var query = new AppDbOper(_db);
var result = await query.InsertAsync(userInfo);
if (result >0)
return new ApiResponseNull(200, "请求成功");
return new ApiResponseNull(200, "请求失败");
}
}
#endregion
#region 修改用户数据
[HttpGet]
public async Task updateUserInfo([FromQuery] UserInfo userInfo)
{
using (_db)
{
await _db.Connection.OpenAsync();
var query = new AppDbOper(_db);
var result = await query.UpdateAsync(userInfo);
if (result > 0)
return new ApiResponseNull(200, "请求成功");
return new ApiResponseNull(200, "请求失败");
}
}
#endregion
#region 根据ID删除数据
[HttpGet]
public async Task delUserInfo(string id)
{
using (_db)
{
await _db.Connection.OpenAsync();
var query = new AppDbOper(_db);
var result = await query.DeleteAllAsync(id);
if (result > 0)
return new ApiResponseNull(200, "请求成功");
return new ApiResponseNull(200, "请求失败");
}
}
#endregion
可以直接在这个页面上,测试自己的接口,每个接口都测试通过。
至此,webapi对数据的增删改查就实现了,恭喜你。
[Route("[controller]")]
//默认路径,如果有多个action会冲突,所以改成这种
[Route("api/[controller]/[action]")]
访问地址
https://localhost:端口/api/控制器/方法
appsettings.json配置全局变量
"ItemName": "xcSharpApi",
"MySettingValue": {
"ItemAddr": "/api/v1/",
"ItemTime": "60"
}
Controller里面调用
public class XcsharpController : ControllerBase
{
public readonly AppDb Db;
private readonly IConfiguration _configuration;
public XcsharpController(AppDb db, IConfiguration configuration)
{
Db = db;
_configuration = configuration;
}
#region 获取系统配置信息
///
/// 获取系统配置信息
///
///
[HttpGet]
public async Task getSysInfo()
{
string name = "";
try
{
name = _configuration["ItemName"];
//name = _configuration.GetSection("MySettingValue")["ItemAddr"];
}
catch (Exception e)
{
name = e.Message;
}
return new ApiResponseNull(200, name);
}
#endregion
}
asp.net core框架搭建1-搭建webapi,对数据增删改查模板(源码) 点击下载
关注博主 带你实现畅游前后端
加入社区 带你体验马航不孤单
神秘个人简介 带你体验不一样得介绍
为爱表白 为你那个TA,体验别致的浪漫惊喜
酷炫邀请函 带你体验高大上得邀请
① 提供云服务部署(有自己的阿里云);
② 提供前端、后端、应用程序、H5、小程序、公众号等相关业务;
如合作请联系我,期待您的联系。
注:本文撰写于CSDN平台,作者:xcLeigh(所有权归作者所有),https://blog.csdn.net/weixin_43151418,如果相关下载没有跳转,请查看这个地址,相关链接没有跳转,皆是抄袭本文,转载请备注本文原地址。
亲,码字不易,动动小手,欢迎 点赞 ➕ 收藏,如 问题请留言(评论),博主看见后一定及时给您答复,
原文地址:https://blog.csdn.net/weixin_43151418/article/details/131458922(防止抄袭,原文地址不可删除)