校园网站建设网站建立网站需要什么
asp.net web api + EF + SQLite+React前端框架
设计一个首页面,包含三个按钮分别对应三类用户(数据查看,设计人员,管理员),当点击管理员的时候弹出一个前端页面可以输入信息(以学生数据为例),提交之后后端存储数据库。当点击数据查看的时候,能够看到管理员录入的所有的学生数据。
1. 后端部分 (ASP.NET Web API + EF + SQLite)
1.1 创建 ASP.NET Web API 项目
-
使用 Visual Studio 或 .NET CLI 创建一个新的 ASP.NET Web API 项目:
dotnet new webapi -n StudentManagementApi cd StudentManagementApi
-
安装必要的 NuGet 包:
dotnet add package Microsoft.EntityFrameworkCore dotnet add package Microsoft.EntityFrameworkCore.Sqlite dotnet add package Microsoft.EntityFrameworkCore.Tools
1.2 配置 SQLite 数据库和 EF Core
-
在
appsettings.json
中配置 SQLite 连接字符串:{"ConnectionStrings": {"DefaultConnection": "Data Source=students.db"} }
-
创建
Student
实体类:public class Student {public int Id { get; set; }public string Name { get; set; }public int Age { get; set; }public string Major { get; set; } }
-
创建
ApplicationDbContext
:
// 定义数据库上下文类,用于与数据库交互
public class ApplicationDbContext : DbContext
{public DbSet<Student> Students { get; set; } // 表示 Students 表// 添加一个接受 DbContextOptions 的构造函数public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options) // 将选项传递给基类{}// 如果需要,可以保留无参构造函数(仅用于手动配置)public ApplicationDbContext(){}
}
- 添加迁移并更新数据库:
dotnet ef migrations add InitialCreate dotnet ef database update
1.3 创建 API 控制器
- 创建
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 应用
-
使用 Create React App 创建前端项目:
npx create-react-app student-management-frontend cd student-management-frontend
-
安装 Axios 用于 HTTP 请求:
npm install axios
2.2 设计首页
- 编辑
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. 功能测试
- 点击“管理员”按钮,填写学生信息并提交。
- 点击“数据查看”按钮,查看管理员录入的学生数据。
- 确保数据能够正确存储到 SQLite 数据库中,并从前端显示出来。