asp.net core框架搭建1-搭建webapi,对数据增删改查接口模板(附源码)

文章目录

  • 系列文章
  • 1.项目搭建
    • 1.1 新建Asp.net core webapi项目
    • 1.2 配置连接Mysql
    • 1.3 实现对mysql数据库的数据增删改查,接口
      • 1.3.1 根据id查询数据
      • 1.3.2 根据用户名模糊查询数据,并分页
      • 1.3.3 新增用户数据
      • 1.3.4 修改用户数据
      • 1.3.5 根据ID删除数据
      • 1.3.6 接口运行效果
  • 2.过程中知识点和涉及到的问题
    • 2.1 自定义路由
    • 2.2 获取可配置的全局变量
  • 源码下载

作者:xcLeigh
文章地址:https://blog.csdn.net/weixin_43151418/article/details/131458922


asp.net core 框架搭建2-搭建webapi ,本文章介绍asp.net core webapi框架搭建,然后开发增删改查和工具接口,将一步步带着大家,实现目标。所有操作过程将展现在本篇文章,下面咋们一起来实现它吧。

系列文章

  • asp.net core 框架搭建1-搭建webapi
  • asp.net core 框架搭建2-搭建MVC后台管理系统
  • asp.net core 框架搭建3-搭建个人博客,公司官网
  • asp.net core 框架搭建4-部署IIS/nguix

1.项目搭建

1.1 新建Asp.net core webapi项目

  • 第一步 新建ASP.NET Core Web API ,选择下一步

asp.net core框架搭建1-搭建webapi,对数据增删改查接口模板(附源码)_第1张图片

  • 第二步 配置新项目,填写自己的项目名称,选择下一步

asp.net core框架搭建1-搭建webapi,对数据增删改查接口模板(附源码)_第2张图片

  • 第三步 其他信息,默认就行,创建项目

asp.net core框架搭建1-搭建webapi,对数据增删改查接口模板(附源码)_第3张图片

  • 第四步 查看项目效果

新建完成后,整体效果图
asp.net core框架搭建1-搭建webapi,对数据增删改查接口模板(附源码)_第4张图片

第五步 运行项目(方式1:直接按F5;方式2:vs2022工具点三角启动,在浏览器中查看),查看效果

界面效果
asp.net core框架搭建1-搭建webapi,对数据增删改查接口模板(附源码)_第5张图片

接口返回数据效果
asp.net core框架搭建1-搭建webapi,对数据增删改查接口模板(附源码)_第6张图片
简单的框架搭建起来了,下面咋们在里面开始操作数据了。

1.2 配置连接Mysql

  • 第一步 通过Nuget引用MySqlConnector

新建表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;
  • 第二步 appsettings.json配置数据库连接字符串
"ConnectionStrings": {
    "MysqlConnection": "Data Source=IP地址;Database=数据库名称;User ID=用户名;Password=密码;port=端口;sslmode=none;CharSet=utf8;pooling=true;"
  },
  • 第三步 封装MySqlConnection连接类

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;
       }
   }

1.3 实现对mysql数据库的数据增删改查,接口

1.3.1 根据id查询数据

#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

1.3.2 根据用户名模糊查询数据,并分页

  • page 第几页
  • limit 页条数
  • username 根据用户名模糊查询
#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

1.3.3 新增用户数据

#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

1.3.4 修改用户数据

#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

1.3.5 根据ID删除数据

#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

1.3.6 接口运行效果

可以直接在这个页面上,测试自己的接口,每个接口都测试通过。

asp.net core框架搭建1-搭建webapi,对数据增删改查接口模板(附源码)_第7张图片

至此,webapi对数据的增删改查就实现了,恭喜你。

2.过程中知识点和涉及到的问题

2.1 自定义路由

[Route("[controller]")]

//默认路径,如果有多个action会冲突,所以改成这种

[Route("api/[controller]/[action]")]

访问地址

https://localhost:端口/api/控制器/方法

2.2 获取可配置的全局变量

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,对数据增删改查模板(源码) 点击下载
asp.net core框架搭建1-搭建webapi,对数据增删改查接口模板(附源码)_第8张图片


     关注博主 带你实现畅游前后端

     加入社区 带你体验马航不孤单

     神秘个人简介 带你体验不一样得介绍

     为爱表白 为你那个TA,体验别致的浪漫惊喜

     酷炫邀请函 带你体验高大上得邀请


     ① 提供云服务部署(有自己的阿里云);
     ② 提供前端、后端、应用程序、H5、小程序、公众号等相关业务;
     如合作请联系我,期待您的联系。
    :本文撰写于CSDN平台,作者:xcLeigh(所有权归作者所有),https://blog.csdn.net/weixin_43151418,如果相关下载没有跳转,请查看这个地址,相关链接没有跳转,皆是抄袭本文,转载请备注本文原地址。


     亲,码字不易,动动小手,欢迎 点赞 ➕ 收藏,如 问题请留言(评论),博主看见后一定及时给您答复,


原文地址:https://blog.csdn.net/weixin_43151418/article/details/131458922(防止抄袭,原文地址不可删除)

你可能感兴趣的:(C#使用,asp.net,后端)