惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

阮一峰的网络日志
阮一峰的网络日志
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
雷峰网
雷峰网
U
Unit 42
Y
Y Combinator Blog
I
InfoQ
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
量子位
Microsoft Security Blog
Microsoft Security Blog
B
Blog
The Cloudflare Blog
F
Fortinet All Blogs
Google DeepMind News
Google DeepMind News
MyScale Blog
MyScale Blog
C
Check Point Blog
S
SegmentFault 最新的问题
爱范儿
爱范儿
博客园 - 叶小钗
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Hugging Face - Blog
Hugging Face - Blog
罗磊的独立博客
T
Tailwind CSS Blog

博客园 - WmW

C#学习牛顿迭代法开方 mysql将一个表中指定时间之后的新数据导入到另一个表中 使用具体时间和DateTime.Now运算时需要注意DateTime.Now的毫秒数 C# 学习研究CRC校验 C# 学习逆变和协变 C# 标准的Dispose模式 C# 返回Task或者Task<T>的方法中如果没有异步方法,就没必要使用async修饰 关于字节序的概念加深 C# 基于ReadOnlySequence和ReadOnlySequenceSegment的简单封装 简单接触BCD码,以及使用C#简单实现BCD转换 C# ReadOnlySequence和ReadOnlySequenceSegment简单使用 C# 非常简单的文字转语音实现 C# 输出年龄和属相列表 C# 封装了一个用来对参数值进行范围限制的泛型方法 C# 为WindowsDefender防火墙已经存在的入站规则添加IP地址 C# 将Framework4.8控制台程序注册为windows服务 C# async void 方法中使用await时外部不会等待 C# Channel学习 C# 使用字符串分割字符串 C# 一个简单的连续心率血氧压缩算法 C# 将日期时间按照ISO 8601标准转成字符串 Dapper传递参数对象时,只支持属性,无法解析字段(出现Parameter '?id' must be defined)
简单搭建一个 ASP.NET Core Web API + Mysql + SqlSugar demo...
WmW · 2026-03-30 · via 博客园 - WmW

新建ASP.NET Core Web API 项目,引用SqlSugarCore包,

新建库UserDB,然后新建表,

CREATE TABLE `user` (
  `UserID` int NOT NULL AUTO_INCREMENT,
  `UserName` varchar(255) NOT NULL,
  `Age` tinyint unsigned NOT NULL,
  `Gender` tinyint unsigned NOT NULL,
  PRIMARY KEY (`UserID`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

Program

using SqlSugar;

namespace WebApplication1 {
    public class Program {
        public static void Main(string[] args) {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            //这个对象应该创建一次就行了吧
            var connectionConfig = new ConnectionConfig() {
                DbType = DbType.MySql,
                ConnectionString = builder.Configuration.GetConnectionString("DefaultConnection"),
                IsAutoCloseConnection = true
            };
            builder.Services.AddScoped<ISqlSugarClient>(s => new SqlSugarClient(connectionConfig));

            var app = builder.Build();

            if (app.Environment.IsDevelopment()) {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UseHttpsRedirection();

            app.UseAuthorization();

            app.MapControllers();

            app.Run();
        }
    }
}

配置文件

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=UserDB;Uid=root;Pwd=123456;"
  }
}

实体类

using SqlSugar;

namespace WebApplication1.Enitiy {
    public class User {
        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
        public int UserID { get; set; }
        public string UserName { get; set; }
        public byte Age { get; set; }
        public byte Gender { get; set; }
    }
}

控制器

using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using WebApplication1.Enitiy;

namespace WebApplication1.Controllers {
    [ApiController]
    [Route("api/[controller]/[Action]")]
    public class UserController(ISqlSugarClient ssc) : ControllerBase {
        [HttpPost]
        public async Task<int> Add([FromForm] User user) {
            return await ssc.Insertable(user).ExecuteCommandAsync();
        }
        //api/User/Delete/1
        [HttpPost("{userID}")]
        public async Task<int> Delete(int userID) {
            return await ssc.Deleteable<User>().Where(s => s.UserID == userID).ExecuteCommandAsync();
        }
        [HttpPost]
        public async Task<int> Update(User user) { //默认解析消息体中的json数据
            return await ssc.Updateable(user).ExecuteCommandAsync();
        }
        //api/User/Get?userID=2
        [HttpGet]
        public async Task<User> Get(int userID) {
            var aaa = await ssc.Queryable<User>().FirstAsync(p => p.UserID == userID);
            return aaa;
        }
        [HttpGet("/api/[controller]/all")] //有时候需要手动指定地址
        public async Task<IEnumerable<User>> GetAll() {
            return await ssc.Queryable<User>().ToListAsync();
        }
        [HttpGet]
        public async Task<IEnumerable<User>> GetListByAge(int age) {
            return await ssc.Queryable<User>().Where(p => p.Age == age).ToListAsync();
        }
        [HttpPost]
        public async Task<IEnumerable<User>> GetListByUserName(string userName) { //默认为query
            return await ssc.Queryable<User>().Where(p => p.UserName == userName).ToListAsync();
        }
        [HttpPost("/api/user/search")]
        public async Task<IEnumerable<User>> GetListLikeUserName([FromForm] string userName) { //解析form标单中的数据
            return await ssc.Queryable<User>().Where(p => p.UserName.Contains(userName)).ToListAsync();
        }
    }
}

注意踩坑:

1,默认新建的项目有个Swagger,如果你顺手升级了Swashbuckle.AspNetCore包,就可能Swagger UI报错异常,此时只需要Ctrl+F5强制刷新清理缓存就正常了

2,即使是POST方式默认参数解析也是去query中找,如果是form表单,需要指定[FromForm],对自定义实体类和基础类型字段都有效

3,手动指定地址时,必须要以/开头才会覆盖默认的路由,比如/api/user/search,否则就是附加,如果配置的是[HttpPost("api/user/search")],最后的地址就会变成https://localhost:7038/api/User/GetListLikeUserName/api/user/search