当前位置: 首页 > news >正文

Asp.Net Web API| React.js| EF框架 | SQLite|

asp.net web api + EF + SQLite+React前端框架

设计一个首页面,包含三个按钮分别对应三类用户(数据查看,设计人员,管理员),当点击管理员的时候弹出一个前端页面可以输入信息(以学生数据为例),提交之后后端存储数据库。当点击数据查看的时候,能够看到管理员录入的所有的学生数据。


1. 后端部分 (ASP.NET Web API + EF + SQLite)

1.1 创建 ASP.NET Web API 项目
  1. 使用 Visual Studio 或 .NET CLI 创建一个新的 ASP.NET Web API 项目:

    dotnet new webapi -n StudentManagementApi
    cd StudentManagementApi
    
  2. 安装必要的 NuGet 包:

    dotnet add package Microsoft.EntityFrameworkCore
    dotnet add package Microsoft.EntityFrameworkCore.Sqlite
    dotnet add package Microsoft.EntityFrameworkCore.Tools
    
1.2 配置 SQLite 数据库和 EF Core
  1. appsettings.json 中配置 SQLite 连接字符串:

    {
      "ConnectionStrings": {
        "DefaultConnection": "Data Source=students.db"
      }
    }
    
  2. 创建 Student 实体类:

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Major { get; set; }
    }
    
  3. 创建 ApplicationDbContext

   // 定义数据库上下文类,用于与数据库交互
public class ApplicationDbContext : DbContext
{
    public DbSet<Student> Students { get; set; } // 表示 Students 表

    // 添加一个接受 DbContextOptions 的构造函数
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options) // 将选项传递给基类
    {
    }
    // 如果需要,可以保留无参构造函数(仅用于手动配置)
    public ApplicationDbContext()
    {
    }
}
  1. 添加迁移并更新数据库:
    dotnet ef migrations add InitialCreate
    dotnet ef database update
    
1.3 创建 API 控制器
  1. 创建 StudentsController
// 定义一个 API 控制器,处理学生数据的增删改查
[Route("api/[controller]")] // 定义路由前缀为 api/students
[ApiController]
public class StudentsController : ControllerBase
{

    private readonly ApplicationDbContext _context; // 注入数据库上下文

    // 构造函数注入
    public StudentsController(ApplicationDbContext context)
    {
        _context = context;
    }

    // GET: api/students - 获取所有学生数据
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Student>>> GetStudents()
    {
        return await _context.Students.ToListAsync(); // 查询并返回所有学生数据
    }

    // POST: api/students - 添加新学生数据
    [HttpPost]
    public async Task<ActionResult<Student>> PostStudent(Student student)
    {
        _context.Students.Add(student); // 将新学生数据添加到数据库
        await _context.SaveChangesAsync(); // 保存更改

        return CreatedAtAction(nameof(GetStudents), new { id = student.Id }, student); // 返回创建的资源
    }

}

2. 前端部分 (React)

2.1 创建 React 应用
  1. 使用 Create React App 创建前端项目:

    npx create-react-app student-management-frontend
    cd student-management-frontend
    
  2. 安装 Axios 用于 HTTP 请求:

    npm install axios
    
2.2 设计首页
  1. 编辑 App.js 文件:
import logo from './logo.svg';
import './App.css';
import React, { useState } from 'react';
import axios from 'axios';

function App() {
    // 定义状态变量,控制是否显示管理员表单
    const [showAdminForm, setShowAdminForm] = useState(false);

    // 定义状态变量,存储从后端获取的学生数据
    const [students, setStudents] = useState([]);

    // 点击 "Admin" 按钮时,显示管理员表单
    const handleAdminClick = () => {
        setShowAdminForm(true);
    };

    // 点击 "Data Viewer" 按钮时,从后端获取所有学生数据
    const handleViewDataClick = async () => {
        try {
            // 发送 GET 请求到后端 API 获取学生数据(要注意一致和后端的api一致)
            const response = await axios.get('https://localhost:5000/api/students');
            // 更新状态变量,存储获取到的学生数据
            setStudents(response.data);
        } catch (error) {
            console.error('Error fetching students:', error);
        }
    };

    // 提交管理员表单时,将学生数据发送到后端
    const handleSubmit = async (event) => {
        event.preventDefault(); // 阻止表单默认提交行为

        // 获取表单输入值
        const name = event.target.name.value;
        const age = event.target.age.value;
        const major = event.target.major.value;

        try {
            // 发送 POST 请求到后端 API 添加学生数据
            await axios.post('https://localhost:5000/api/students', { name, age, major });
            alert('Student added successfully!'); // 提示用户操作成功
            setShowAdminForm(false); // 隐藏表单
        } catch (error) {
            console.error('Error adding student:', error);
        }
    };

    return (
        <div>
            {/* 页面标题 */}
            <h1>Welcome to Student Management System</h1>

            {/* 功能按钮 */}
            <button onClick={handleAdminClick}>Admin</button>
            <button onClick={handleViewDataClick}>Data Viewer</button>
            <button>Designer</button>

            {/* 管理员表单 */}
            {showAdminForm && (
                <form onSubmit={handleSubmit}>
                    <h2>Add Student</h2>
                    {/* 输入学生姓名 */}
                    <input type="text" name="name" placeholder="Name" required />
                    {/* 输入学生年龄 */}
                    <input type="number" name="age" placeholder="Age" required />
                    {/* 输入学生专业 */}
                    <input type="text" name="major" placeholder="Major" required />
                    {/* 提交按钮 */}
                    <button type="submit">Submit</button>
                </form>
            )}

            {/* 显示学生数据 */}
            {students.length > 0 && (
                <div>
                    <h2>Student List</h2>
                    <ul>
                        {/* 遍历学生数据并显示 */}
                        {students.map((student) => (
                            <li key={student.id}>
                                {student.name} - {student.age} years old - {student.major}
                            </li>
                        ))}
                    </ul>
                </div>
            )}
        </div>
    );
}

export default App;

3. 运行项目

3.1 启动后端

在后端项目目录下运行:

dotnet run

API 将在 http://localhost:5000 上运行。
运行成功后,弹出swagger UI页面,测试API接口是否正常;在这里插入图片描述

3.2 启动前端

在前端项目目录下运行:

npm start

React 应用将在 http://localhost:3000 上运行。


4. 功能测试

  1. 点击“管理员”按钮,填写学生信息并提交。
  2. 点击“数据查看”按钮,查看管理员录入的学生数据。
  3. 确保数据能够正确存储到 SQLite 数据库中,并从前端显示出来。

相关文章:

  • Excel的两个小问题解决
  • 如何将图片档案信息读取出来?并把档案信息相关性进行关联
  • Spark技术系列(二):深入理解RDD编程模型——从原理到生产实践
  • 使用Apache Lucene构建高效的全文搜索服务
  • Android双屏异显副屏实现PIP效果小窗口同步显示主屏播放画面
  • gcc编译器优化
  • PHP如何与HTML结合使用?
  • ApplicationContextInitializer
  • 编译和链接
  • 中央一号文件里的三维革命:数字孪生如何重构智慧乡村生态?
  • 蓝桥杯 成绩统计
  • PhotoDoodle: Learning Artistic Image Editing from Few-Shot Examples 论文解读
  • 两个桌面图标助手,你喜欢哪一个
  • uniapp vue3实现的一款数字动画调节器件,支持长按、单点操作,提供丝滑的增减动画效果
  • 03.04、化栈为队
  • 次日留存率——mysql计算过程
  • 【北大Deepseck】最新2份pdf(附不限速链接) 系列-提示词工程和落地场景 DeepSeek与AIGC应用
  • 【FL0087】基于SSM和微信小程序的民宿短租系统
  • Qt之3D绘制曲线:QtDataVisualization实时绘制散点图
  • 网络原理--IP协议简介
  • 我国成功发射中星3B卫星
  • F4方程式上海站引擎轰鸣,见证中国赛车运动不断成长
  • 遇见东方:18世纪俄罗斯宫殿中的“中国风”
  • 证监会副主席李明:支持符合条件的外资机构申请新业务、设立新产品
  • 广东进入“倒水模式”,珠江防总、珠江委已启动Ⅳ级应急响应
  • 梅花奖在上海|秦海璐:演了15年《四世同堂》,想演一辈子