netcore入门案例:netcore api连接mysql的完整记事本接口示例

news/2025/2/28 16:22:15/

以下是一个使用 .NET Core API 连接 MySQL 数据库实现简单记事本功能的完整示例,包含创建、读取、更新和删除(CRUD)操作。

1. 创建 .NET Core Web API 项目

首先,打开命令行工具,使用以下命令创建一个新的 .NET Core Web API 项目:

dotnet new webapi -n NotePadAPI
cd NotePadAPI

2. 安装 MySQL 数据库驱动

在项目目录下,使用以下命令安装 MySQL 数据库驱动:

dotnet add package MySqlConnector

3. 配置数据库连接字符串

打开 appsettings.json 文件,添加 MySQL 数据库连接字符串:

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

请将 your_usernameyour_password 替换为你的 MySQL 用户名和密码。

4. 创建数据库和表

在 MySQL 中创建一个名为 notepad数据库,并创建一个名为 notes 的表:

CREATE DATABASE notepad;USE notepad;CREATE TABLE notes (id INT AUTO_INCREMENT PRIMARY KEY,title VARCHAR(255) NOT NULL,content TEXT NOT NULL,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

5. 创建数据模型

Models 文件夹下创建 Note.cs 文件:

using System;namespace NotePadAPI.Models
{public class Note{public int Id { get; set; }public string Title { get; set; }public string Content { get; set; }public DateTime CreatedAt { get; set; }}
}

6. 创建数据库上下文

Data 文件夹下创建 NoteContext.cs 文件:

using Microsoft.Data.SqlClient;
using MySqlConnector;
using NotePadAPI.Models;
using System.Collections.Generic;
using System.Data;namespace NotePadAPI.Data
{public class NoteContext{private readonly string _connectionString;public NoteContext(string connectionString){_connectionString = connectionString;}public List<Note> GetAllNotes(){var notes = new List<Note>();using (var connection = new MySqlConnection(_connectionString)){var query = "SELECT * FROM notes";var command = new MySqlCommand(query, connection);connection.Open();var reader = command.ExecuteReader();while (reader.Read()){notes.Add(new Note{Id = reader.GetInt32("id"),Title = reader.GetString("title"),Content = reader.GetString("content"),CreatedAt = reader.GetDateTime("created_at")});}reader.Close();}return notes;}public Note GetNoteById(int id){using (var connection = new MySqlConnection(_connectionString)){var query = "SELECT * FROM notes WHERE id = @id";var command = new MySqlCommand(query, connection);command.Parameters.AddWithValue("@id", id);connection.Open();var reader = command.ExecuteReader();if (reader.Read()){return new Note{Id = reader.GetInt32("id"),Title = reader.GetString("title"),Content = reader.GetString("content"),CreatedAt = reader.GetDateTime("created_at")};}reader.Close();}return null;}public void CreateNote(Note note){using (var connection = new MySqlConnection(_connectionString)){var query = "INSERT INTO notes (title, content) VALUES (@title, @content)";var command = new MySqlCommand(query, connection);command.Parameters.AddWithValue("@title", note.Title);command.Parameters.AddWithValue("@content", note.Content);connection.Open();command.ExecuteNonQuery();}}public void UpdateNote(Note note){using (var connection = new MySqlConnection(_connectionString)){var query = "UPDATE notes SET title = @title, content = @content WHERE id = @id";var command = new MySqlCommand(query, connection);command.Parameters.AddWithValue("@title", note.Title);command.Parameters.AddWithValue("@content", note.Content);command.Parameters.AddWithValue("@id", note.Id);connection.Open();command.ExecuteNonQuery();}}public void DeleteNote(int id){using (var connection = new MySqlConnection(_connectionString)){var query = "DELETE FROM notes WHERE id = @id";var command = new MySqlCommand(query, connection);command.Parameters.AddWithValue("@id", id);connection.Open();command.ExecuteNonQuery();}}}
}

7. 创建控制器

Controllers 文件夹下创建 NotesController.cs 文件:

using Microsoft.AspNetCore.Mvc;
using NotePadAPI.Data;
using NotePadAPI.Models;
using System.Collections.Generic;namespace NotePadAPI.Controllers
{[ApiController][Route("api/[controller]")]public class NotesController : ControllerBase{private readonly NoteContext _context;public NotesController(NoteContext context){_context = context;}[HttpGet]public ActionResult<IEnumerable<Note>> GetAllNotes(){var notes = _context.GetAllNotes();return Ok(notes);}[HttpGet("{id}")]public ActionResult<Note> GetNoteById(int id){var note = _context.GetNoteById(id);if (note == null){return NotFound();}return Ok(note);}[HttpPost]public ActionResult<Note> CreateNote(Note note){_context.CreateNote(note);return CreatedAtAction(nameof(GetNoteById), new { id = note.Id }, note);}[HttpPut("{id}")]public IActionResult UpdateNote(int id, Note note){if (id != note.Id){return BadRequest();}_context.UpdateNote(note);return NoContent();}[HttpDelete("{id}")]public IActionResult DeleteNote(int id){_context.DeleteNote(id);return NoContent();}}
}

8. 配置服务

打开 Program.cs 文件,配置数据库上下文:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NotePadAPI.Data;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();// Configure database context
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddSingleton(new NoteContext(connectionString));var app = builder.Build();// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{app.UseSwagger();app.UseSwaggerUI();
}app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();

9. 运行项目

在命令行中运行以下命令启动项目:

dotnet run

10. 测试 API

你可以使用 Postman 或其他 API 测试工具来测试以下接口:

  • 获取所有笔记GET http://localhost:5000/api/notes
  • 获取单个笔记GET http://localhost:5000/api/notes/{id}
  • 创建笔记POST http://localhost:5000/api/notes,请求体为 JSON 格式的笔记信息。
  • 更新笔记PUT http://localhost:5000/api/notes/{id},请求体为 JSON 格式的更新后的笔记信息。
  • 删除笔记DELETE http://localhost:5000/api/notes/{id}

通过以上步骤,你就可以实现一个简单的记事本 API,使用 .NET Core 连接 MySQL 数据库进行数据的 CRUD 操作。


http://www.ppmy.cn/news/1575545.html

相关文章

2025年02月27日Github流行趋势

项目名称&#xff1a;aibrix 项目地址url&#xff1a;https://github.com/vllm-project/aibrix 项目语言&#xff1a;Jupyter Notebook 历史star数&#xff1a;2568 今日star数&#xff1a;554 项目维护者&#xff1a;Jeffwan, varungup90, brosoul, nwangfw, kr11 项目简介&am…

如何在 WPS 中集成 DeepSeek

如何在 WPS 中集成 DeepSeek&#xff1a;从零基础到高阶开发的完整指南 DeepSeek 作为国内领先的 AI 办公助手&#xff0c;与 WPS 的深度整合可显著提升文档处理效率。本文提供 ​4 种集成方案&#xff0c;覆盖从「小白用户」到「企业开发者」的全场景需求&#xff0c;并包含 …

Redis 底层数据结构 —— SDS(简单动态字符串)

文章目录 前言一、SDS是什么&#xff1f;二、为什么要采用SDS?三、SDS结构详解3.1 SDS 类型定义3.2 SDS结构组成 四、SDS的预分配内存五、再谈为什么要采用SDS?六、总结 前言 我们都知道redis是用c语言实现的&#xff0c;但是c语言并没有字符串结构&#xff0c;而是通过字符…

【弹性计算】Guest OS

Guest OS 1.基础架构2.成本效率优化2.1 保障兼容性、简化生态环境&#xff0c;解决方案一键部署2.2 提升资源弹性和资源利用率2.2.1 系统资源的量化和监控2.2.2 资源隔离能力 3.安全性和稳定性增强3.1 安全性3.2 RAS3.2.1 可靠性&#xff08;Reliability&#xff09;3.2.2 可用…

jspssm542Springboot 医疗服务系统

&#x1f4d8; 博主小档案&#xff1a; 花花&#xff0c;一名来自世界500强的资深程序猿&#xff0c;毕业于国内知名985高校。 &#x1f527; 技术专长&#xff1a; 花花在深度学习任务中展现出卓越的能力&#xff0c;包括但不限于java、python等技术。近年来&#xff0c;花花更…

Linux | RHEL / CentOS 中 YUM history / downgrade 命令回滚操作

注&#xff1a;英文引文&#xff0c;机翻未校。 在 RHEL/CentOS 系统上使用 YUM history 命令回滚升级操作 作者&#xff1a; 2daygeek 译者&#xff1a; LCTT DarkSun 为服务器打补丁是 Linux 系统管理员的一项重要任务&#xff0c;为的是让系统更加稳定&#xff0c;性能更加…

Golang学习笔记_39——策略模式

Golang学习笔记_36——装饰器模式 Golang学习笔记_37——外观模式 Golang学习笔记_38——享元模式 文章目录 一、核心概念1. 定义2. 解决的问题3. 核心角色4. 类图 二、特点分析三、适用场景1. 支付系统2. 数据压缩3. 游戏AI4. 折扣计算 四、代码示例&#xff08;Go语言&#x…

国内短剧系统源码部署小程序体验测评讲解

在移动互联网飞速发展的今天&#xff0c;短剧作为一种新兴的娱乐形式&#xff0c;凭借其短小精悍、内容丰富的特点&#xff0c;迅速赢得了大量用户的青睐。作为一名软件测试人员&#xff0c;我有幸深入体验了一款功能全面、设计精良的短剧小程序。本文将从前端设计、后端功能、…