【问题标题】:MVC Routing in .NET Core React project isn't picking up my Controller.NET Core React 项目中的 MVC 路由没有选择我的控制器
【发布时间】:2019-12-22 06:48:03
【问题描述】:

我正在学习如何使用 ASP.NET Core 创建 React 应用程序。作为一个新手,我从一开始就尝试在主页上显示“Hello World”。我已经使用 Visual Studio 的默认 React.js 项目模板来帮助我入门。路由设置为默认值。这是我的文件:

Home.js:

import React, { Component } from 'react';

export class Home extends Component {

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

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

    }

  render () {
      return (

            <h1>{this.state.message}</h1>

    );
  }
}

HomeController.cs:

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


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

问题在于被解析为 Json 的 HTTP 响应不是正确的。我已将其 console.logged 以尝试调试,似乎response.json()) 正在检索模板应用程序附带的默认public/index.html 文件中的所有文本。有谁知道这是为什么?

如果我遗漏了一些非常明显的东西,我深表歉意 - 我使用的是 Mac,因此文件结构和 Visual Studio IDE 完全不同,我已经很难理解其中的很多教程/答案。

【问题讨论】:

  • 你能解决这个问题吗?在点击控制器方法时我遇到了同样的问题。我收到“您需要启用 JavaScript 才能运行此应用程序”。这是 react app @juemura7 中 index.html 的默认消息
  • 嗨@DevProf - 在我的例子中,我用public string Message()替换了public async Task&lt;string&gt; Message()

标签: c# reactjs model-view-controller routing


【解决方案1】:

要访问您的 Message() 函数,您必须对 'api/Home' 而不是 'api/Home/Message' 进行 HttpGet。

如果您希望端点为 'api/Home/Message',那么您必须为 Message() 函数指定路由,如下所示:

// api/Home/Message
[HttpGet, Route("Message")]
public async Task<IActionResult> Message()

【讨论】:

  • 谢谢,但这仍然不起作用,正在返回 index.html :(
【解决方案2】:

Controller 类用于生成完整网页的 MVC。

对于 Web API,您需要扩展 ControllerBase。你应该直接返回你的值/对象:

[Route("api/[controller]")]
[ApiController]
public class HomeController :  ControllerBase
{
    [HttpGet, Route("message")]
    public async Task<string> Message()
    {
        var response = "Hello World";
        return response;
    }
}

【讨论】:

  • 谢谢@MichaelDomashchenko - 感谢您的帮助。不幸的是,发生了同样的错误:(
  • 您仍然从服务器取回整个 index.html 吗?您现在应该直接收到您的信息。问题可能是单个字符串不完全是 json。在 Chrome 中的 .then(response 行上放置一个断点。有什么回应?
  • 嗨@MichaelDomashchenko - 是的,它仍然返回整个 index.html 而不是消息。 .then(response) 返回此错误:Uncaught (in promise) SyntaxError: Unexpected token &lt; in JSON at position 0 和 index.html 代码:&lt;!DOCTYPE html&gt;...
  • @jordantomiko,@Noremac 是正确的,对于 API 控制器,您需要使用方法级别的 Route 属性显式指定 message 段。尝试将[ApiController] 添加到您的班级,尽管对我来说它是双向的。此外,请尝试在 appsettings.Development.json 文件中为所有日志记录(包括系统和 Microsoft)启用“调试”级别,这可能会提供额外的线索。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-02
  • 1970-01-01
  • 2021-05-17
  • 1970-01-01
相关资源
最近更新 更多