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

推荐订阅源

S
Securelist
C
Cybersecurity and Infrastructure Security Agency CISA
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Security Affairs
Hacker News: Ask HN
Hacker News: Ask HN
L
Lohrmann on Cybersecurity
PCI Perspectives
PCI Perspectives
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
Cyber Attacks, Cyber Crime and Cyber Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
MyScale Blog
MyScale Blog
月光博客
月光博客
W
WeLiveSecurity
T
Threat Research - Cisco Blogs
Martin Fowler
Martin Fowler
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Recorded Future
Recorded Future
The GitHub Blog
The GitHub Blog
Webroot Blog
Webroot Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
TaoSecurity Blog
TaoSecurity Blog
P
Proofpoint News Feed
Google DeepMind News
Google DeepMind News
F
Full Disclosure
U
Unit 42
Jina AI
Jina AI
博客园 - 司徒正美
阮一峰的网络日志
阮一峰的网络日志
L
LINUX DO - 最新话题
宝玉的分享
宝玉的分享
大猫的无限游戏
大猫的无限游戏
The Hacker News
The Hacker News
The Last Watchdog
The Last Watchdog
T
Troy Hunt's Blog
腾讯CDC
T
Threatpost
H
Hacker News: Front Page
P
Palo Alto Networks Blog
博客园 - 聂微东
Last Week in AI
Last Week in AI
有赞技术团队
有赞技术团队
Help Net Security
Help Net Security
L
LINUX DO - 热门话题
N
News and Events Feed by Topic
人人都是产品经理
人人都是产品经理
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Spread Privacy
Spread Privacy

博客园 - BloggerSb

Swagger 文档设置api版本 .Net Core Routing Demo .net Core读取配置比较 简化版DbExecutor,将DataTable映射到T属性(支持Dapper风格的匿名参数)。(编程题) 大文件单词统计 (编程题) 设计模式落地:Repository + UnitOfWork + CQRS 完整实现 (编程题) 给定百万级订单表,实现高效分页 + 动态条件查询 + 导出 Excel(避免内存爆炸) (编程题) 实现一个带 CorrelationId、请求日志、异常统一处理的中间件链 (编程题) 异步限流器实现(编程题) 编程题,记录所有接口的执行耗时 .net面试题目 (问答题) 面试高频简答题 Aspose最新Slides破解 HttpContext.User.Identity.IsAuthenticated 为false 关于Cannot resolve scoped service from root provider解决方案 MongoDB用户权限管理,设置密码并连接 mongodb连接字符串 mongodb 使用 MongoDB Compass 创建账号,角色 安装mongodb bootstrap popover 设置悬浮框宽度 div contenteditable="true" 添加placehoder效果 光标自动定位到起始位置contenteditable="true" ,v-html绑定内容,div可编辑时,光标移到最前面
ASP.NET Core CRUD API 创建 UserController,实现 Get, Post, Put, Delete 方法,使用 EF Core 访问数据库。 (编程题)
BloggerSb · 2026-04-17 · via 博客园 - BloggerSb

ASP.NET Core CRUD API - 创建 UserController,实现 Get, Post, Put, Delete 方法,使用 EF Core 访问数据库。

Install-Package Microsoft.EntityFrameworkCore Install-Package Microsoft.EntityFrameworkCore.SqlServer # SQL Server 数据库 Install-Package Microsoft.EntityFrameworkCore.Tools

在项目中新建 Models 文件夹,创建 User.cs
namespace UserCRUDAPI.Models
{
    // 用户实体(对应数据库表)
    public class User
    {
        public int Id { get; set; } // 主键,自增
        public string UserName { get; set; } = string.Empty; // 用户名
        public string Email { get; set; } = string.Empty; // 邮箱
        public int Age { get; set; } // 年龄
    }
}

新建 Data 文件夹,创建 AppDbContext.cs
using Microsoft.EntityFrameworkCore;
using UserCRUDAPI.Models;

namespace UserCRUDAPI.Data
{
    // 数据库上下文:连接 EF Core 和数据库
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }

        // 对应数据库中的 Users 表
        public DbSet<User> Users => Set<User>();
    }
}


打开 appsettings.json,添加连接字符串(修改为你的 SQL Server 地址)
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  // 数据库连接字符串
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=UserCRUDDB;Trusted_Connection=True;TrustServerCertificate=True;"
  }
}
在 Program.cs 中注入数据库上下文:
using Microsoft.EntityFrameworkCore;
using UserCRUDAPI.Data;

var builder = WebApplication.CreateBuilder(args);

// 添加控制器
builder.Services.AddControllers();

// 注册 EF Core + SQL Server
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// Swagger(接口测试工具)
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// 开发环境启用 Swagger
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

打开 程序包管理器控制台 执行:
Add-Migration InitialCreate # 创建迁移文件 
Update-Database # 生成数据库和表

执行成功后,会自动创建 UserCRUDDB 库和 Users 表。

在 Controllers 文件夹创建 UserController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using UserCRUDAPI.Data;
using UserCRUDAPI.Models;

namespace UserCRUDAPI.Controllers
{
    [Route("api/[controller]")]  // 路由:api/User
    [ApiController]              // 自动模型验证、API 特性
    public class UserController : ControllerBase
    {
        private readonly AppDbContext _context;

        // 构造函数注入数据库上下文
        public UserController(AppDbContext context)
        {
            _context = context;
        }

        // ======================== 1. 获取所有用户 ========================
        [HttpGet]
        public async Task<ActionResult<IEnumerable<User>>> GetUsers()
        {
            return await _context.Users.ToListAsync();
        }

        // ======================== 2. 根据ID获取单个用户 ========================
        [HttpGet("{id}")]
        public async Task<ActionResult<User>> GetUser(int id)
        {
            var user = await _context.Users.FindAsync(id);

            if (user == null)
            {
                return NotFound(); // 返回 404
            }

            return user;
        }

        // ======================== 3. 修改用户 ========================
        [HttpPut("{id}")]
        public async Task<IActionResult> PutUser(int id, User user)
        {
            if (id != user.Id)
            {
                return BadRequest(); // 传入ID与实体ID不匹配
            }

            _context.Entry(user).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent(); // 返回 204 成功无内容
        }

        // ======================== 4. 新增用户 ========================
        [HttpPost]
        public async Task<ActionResult<User>> PostUser(User user)
        {
            _context.Users.Add(user);
            await _context.SaveChangesAsync();

            // 返回 201 + 创建的资源地址
            return CreatedAtAction("GetUser", new { id = user.Id }, user);
        }

        // ======================== 5. 删除用户 ========================
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteUser(int id)
        {
            var user = await _context.Users.FindAsync(id);
            if (user == null)
            {
                return NotFound();
            }

            _context.Users.Remove(user);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        // 辅助方法:判断用户是否存在
        private bool UserExists(int id)
        {
            return _context.Users.Any(e => e.Id == id);
        }
    }
}