为什么新控制器不适用于 .NET Core 6 上的 React Template

Dar*_*mos 9 c# reactjs asp.net-core asp.net-core-webapi

我正在使用 ASP.NET Core 6 Web API 和 React 入门模板开始编写代码,但经过几个小时的研究,我无法弄清楚出了什么问题。

该模板有这个控制器:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }

    [HttpGet("test")]
    public Object Test()
    {
        return new int [] {};
    }
}
Run Code Online (Sandbox Code Playgroud)

我创建了该方法Test并导航到/weatherforecast/test,我正确地得到了一个空数组,但是当我创建新控制器并尝试访问新端点时,我的问题出现了。服务器将我重定向到index.html页面

这是一个控制器示例

[ApiController]
[Route("api/[controller]")]
public class WeatherController : ControllerBase
{
    [HttpGet]
    public Object Get()
    {
        return new int [] {};
     }
 }
Run Code Online (Sandbox Code Playgroud)

我测试了[Route("[controller]")],[Route("weather")]并输入浏览器 url/weather或 ,/api/weather并且我总是看到带有顶部导航栏的主页,我希望返回一个带有空数组的 json 结果。请提供任何帮助,我们将不胜感激。

这是文件的内容Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    // The default HSTS value is 30 days. You may want to change this for production 
    scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

app.MapFallbackToFile("index.html");

app.Run();
Run Code Online (Sandbox Code Playgroud)

AxC*_*der 8

就我而言,它是通过以下步骤解决的:

  1. 打开 ClientApp\src\setupProxy.js
  2. 将所需的路径添加到contextconst 中:
const context =  [
  "/weatherforecast",
  "/api" // <-- this is an added item
];
Run Code Online (Sandbox Code Playgroud)

我的直观理解是,默认模板正在运行一些 React 开发 http 服务器,该服务器通过此文件中配置的模式将请求重定向到 ASP.NET core 服务器。

如果请求的路径与模式不匹配,它会自行提供服务,因此我们的请求不会到达 ASP.NET Core 服务器。


小智 0

Net 6 React 模板通过本地部署到不同的端口,将前端(React)与后端(C# Web api)分开。您可以检查 launchSettings.json 以查看正在部署的应用程序的端口: "applicationUrl": "https://localhost:7027;http://localhost:5027",

如果您在那里找不到它,请检查 ClientApp/src/setupProxy.js 以查看正在使用的端口:

const 目标 = env.ASPNETCORE_HTTPS_PORT ?https://localhost:${env.ASPNETCORE_HTTPS_PORT}:env.ASPNETCORE_URLS?env.ASPNETCORE_URLS.split(';')[0] : 'http://localhost:6973';