React集成ASP.NET Core后无法显示数据库数据问题排查
React + ASP.NET Core 6.0 无法显示Student表数据问题排查
我正在学习将React与ASP.NET Core应用集成,创建了基于.NET 6.0、SQL Server数据库的React+ASP.NET Core项目,目前遇到的问题是:页面仅显示表格表头,无法加载数据库中的Student数据。以下是相关代码:
StudentController.cs 代码
[Route("api/[controller]")] [ApiController] public class StudentController : ControllerBase { private readonly ApplicationDbContext _dbcontext; public StudentController(ApplicationDbContext dbcontext) { _dbcontext = dbcontext; } [HttpGet] [Route("GetStudents")] public IActionResult GetStudents() { List<Student> students =_dbcontext.Student.ToList(); return StatusCode(StatusCodes.Status200OK, students); } }
Student.js 代码
import {React, useEffect, useState } from "react"; const App = () => { //create useState const [students, setStudents] = useState([]) //call api useEffect(() => { fetch("api/Student/GetStudents") .then(response => { return response.json() }) .then(responseJson => { setStudents(responseJson) }) }, []) return ( <div className="container"> <h1>Students</h1> <div className="row"> <div className="col-12"> <table className="table table-stripped table-bordered"> <thead> <tr> <th>Id</th> <th>Student Name</th> <th>Course Enrolled</th> </tr> </thead> <tbody> { students.map((item) => ( <tr> <td>{item.Id}</td> <td>{item.Name}</td> <td>{item.Course}</td> </tr> )) } </tbody> </table> </div> </div> </div> ) } export default App;
AppRoutes.js 代码
import { default as Student } from "./components/Student"; const AppRoutes = [ { path: '/students', element: <Student /> } ]; export default AppRoutes;
可能的问题及解决方法
1. API 请求路径或跨域问题
- 若前端是独立项目(如create-react-app创建),需使用完整API地址,例如
fetch("http://localhost:5000/api/Student/GetStudents"),同时后端需配置跨域(CORS):
在Program.cs中添加:builder.Services.AddCors(options => { options.AddPolicy("AllowAll", policy => { policy.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); app.UseCors("AllowAll"); - 打开浏览器F12的Network标签,查看请求状态码:404表示路径错误,500表示后端接口异常。
2. 后端接口未返回有效数据
- 确认
ApplicationDbContext中已声明DbSet<Student> Student { get; set; },且数据库连接字符串配置正确。 - 在
GetStudents方法中添加调试逻辑,验证是否查询到数据:[HttpGet("GetStudents")] public IActionResult GetStudents() { var students = _dbcontext.Student.ToList(); // 断点查看students数量,或用日志记录 return Ok(students); // 推荐用Ok()替代StatusCode(200, ...),语义更清晰 } - 检查SQL Server中Student表是否存在数据。
3. 前端数据字段不匹配
-.NET 6默认JSON序列化会将C#的PascalCase(如Id)转为camelCase(如id),前端需对应使用小写字段名:
修改Student.js中的映射部分:
<tr> <td>{item.id}</td> <td>{item.name}</td> <td>{item.course}</td> </tr>
- 在前端
fetch中添加错误捕获和数据打印,确认返回格式:useEffect(() => { fetch("api/Student/GetStudents") .then(response => { if (!response.ok) throw new Error(`状态码:${response.status}`); return response.json(); }) .then(responseJson => { console.log("返回数据:", responseJson); setStudents(responseJson); }) .catch(err => console.error("请求错误:", err)); }, []);
4. React路由配置缺失
- 确保主App组件已正确配置React Router(以v6为例):
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; import AppRoutes from './AppRoutes'; function RootApp() { return ( <Router> <Routes> {AppRoutes.map((route, idx) => ( <Route key={idx} path={route.path} element={route.element} /> ))} </Routes> </Router> ); } export default RootApp; - 确认访问路径为
/students,而非根路径(若根路径未映射到Student组件)。
内容的提问来源于stack exchange,提问作者user3309231
相关产品推荐
相关产品推荐

