You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#读取JSON文件返回API数据无法渲染到React页面问题求助

修复方案

1. 修复React fetch调用的两个错误

你当前的代码有两个直接导致数据无法渲染的问题:

  • 链式.then的传参错误:第一个.then(setTitle(res.title))执行后没有返回接口响应对象,后续所有.then拿到的入参都是undefined
  • 字段大小写不匹配:C#接口返回的JSON字段首字母为大写,你调用时用了小写的res.title,自然取不到值

直接替换fetchData方法即可:

const fetchData = () => {
    fetch("api/aboutMe")
        .then((res) => res.json())
        .then(res => {
            // 统一在同一个回调里处理状态赋值,字段名和接口返回的大写格式保持一致
            setTitle(res.Title)
            setName(res.Name)
            setLocation(res.Location)
            setDescription(res.Description)
        })
        .catch(err => {
            console.error("请求出错:", err)
            setErrors(true)
        });
}

2. 可选优化(避免后续运行异常)

2.1 补全Controller的继承关系

你的AboutController没有继承ControllerBase,属于非规范写法,补全后代码如下:

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using PortfolioSite.Models;

namespace PortfolioSite.Controllers
{
    [ApiController]
    [Route("api/aboutMe")]
    // 加上ControllerBase继承
    public class AboutController : ControllerBase
    {
        [HttpGet]
        public AboutMe GetAboutInfo()
        {
            string jsonText = System.IO.File.ReadAllText("./Data/AboutMe.json");
            return JsonConvert.DeserializeObject<AboutMe>(jsonText);
        }
    }
}
2.2 配置JSON文件的复制规则

在IDE中右键点击Data/AboutMe.json文件,选择「属性」,将「复制到输出目录」设置为「如果较新则复制」,避免运行时找不到JSON文件的问题。


内容的提问来源于stack exchange,提问作者Maria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 19:15:01