【问题标题】:ASP.NET Core React project template - how to link to C# backendASP.NET Core React 项目模板 - 如何链接到 C# 后端
【发布时间】:2019-08-15 19:03:12
【问题描述】:

我正在尝试学习如何使用 ASP.NET Core 创建 React 应用程序。很有帮助的是,他们提供了 React 项目模板,其中一些示例使我能够了解一切是如何协同工作的。但是,为了确保我完全理解,我想添加我自己的代码。我从“Hello World”开始 v. small - 我只想在主页上显示它。

这是我的 home.js 文件:

import React, { Component } from 'react';

export class Home extends Component {
static displayName = Home.name;

   constructor(props) {
      super(props);
      this.state = { message: "" };

        fetch('Home/Index')
           .then(res => res.json())
           .then((result) => {
           this.setState({ message: result.message });
         });
    }

        render () {
         return (
           <div>
             <h1>Message:{this.state.message}</h1>
           </div> 
        );
    }
}

这是我希望在主页上呈现的后端代码: HomeController.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;


namespace TestingReactDotNet.Controllers
{
    public class HomeController : Controller
    {
        // GET: /<controller>/
        public string Index()
        {
            return "Hello World";
        }
    }
}

我的问题是 - 我在 Home.js 中 return() 将代码合并到 HomeController.cs 并显示 "hello world" 是什么?

抱歉,如果这个问题似乎已在其他地方得到解答 - 我使用的是 Mac,因此文件结构和 Visual Studio IDE 完全不同,我很难理解已经存在的许多教程/答案。

【问题讨论】:

  • 您需要从您的 react 应用程序对 .net 核心应用程序的 Index 方法进行 ajax 调用,并以这种方式检索字符串“Hello World”。一旦你得到响应,就需要在反应端添加一个变量,并让它在渲染器的返回语句中渲染。
  • 非常感谢@Chris - 我试图对 .net 核心应用程序的 Index 方法进行 ajax 调用(我已经编辑了我的原始帖子以显示我的尝试!)这不起作用(它什么都不显示)所以我一定是哪里出错了?

标签: c# asp.net reactjs


【解决方案1】:

对于客户端部分,您需要从客户端应用程序向 API 发出 http 请求。确实,您在 cmets 中提到的 ajax 请求。无论您使用何种前端库/框架,这几乎都是一样的。

有几种方法可以解决这个问题,但一个简单的开箱即用方法 - 如果您以现代浏览器为目标 - 是使用native Fetch API

import React, { Component } from 'react';

export class Home extends Component {
  constructor (props) {
    super(props);
    this.state = { message: '' };

    fetch('api/home/')
      .then(response => response.json())
      .then(data => {
        this.setState({ 
            message: data 
        });
      });
  }

  render () {
    return (
        <h1>{this.state.message}</h1>
    );
  }
}

发出 http 请求的另一种方法是进入 native XmlHttpRequest,或使用第三方库(例如 axios)来抽象出这种复杂性。

至于服务器端的 api,我假设您了解并已将其配置为在 api/home/ 上可用。稍加优化将使您的控制器示例如下所示:

[Route("api/[controller]")]
public class HomeController : Controller
{
    [HttpGet]
    public async Task<IActionResult> Index()
    {
        var response = "Hello World";
        return Ok(response);
    }
}

【讨论】:

  • 非常感谢!真的很有帮助!我已将我的代码更改为您的建议。但是,屏幕上仍然没有显示任何内容 :( 不过谢谢!
  • @jordantomiko 您的浏览器控制台有错误吗?你能识别 + 将完整的 url 放到浏览器中的 api 中,看看它是否给出了正确的返回?
  • 控制台错误是:“Uncaught (in promise) SyntaxError: Unexpected token
  • 我已经尝试 console.logging out 在我的 response.json() 中被解析为 .json 的内容,并且由于某种原因,获取请求正在返回我的 index.html 文件中的内容而不是什么在我的 HomeController.cs 文件中。你知道为什么会这样吗?
猜你喜欢
  • 2021-10-24
  • 1970-01-01
  • 2020-11-13
  • 1970-01-01
  • 2019-02-09
  • 1970-01-01
  • 2023-03-05
  • 2018-02-03
  • 2021-06-14
相关资源
最近更新 更多