控制器在带有 React 的 .NET Core 中无法工作(WeatherForecast 除外)

Axi*_*ili 3 asp.net-core-mvc asp.net-core asp.net-core-webapi

使用 React.js 创建了一个新的 .NET Core项目,默认情况下它位于Program.cs

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

app.MapFallbackToFile("index.html"); ;
Run Code Online (Sandbox Code Playgroud)

提供的WeatherForecastController作品,即这个作品:

https://localhost:44449/weatherforecast
Run Code Online (Sandbox Code Playgroud)

但是如果我照搬这样WeatherForecastController.cs命名的话MyNewController.cs,就不行了。

[ApiController]
[Route("[controller]")]
public class MyNewController : ControllerBase
{
   ...
Run Code Online (Sandbox Code Playgroud)

https://localhost:44449/mynew返回index.html的内容。

我缺少什么?

小智 7

您必须在上下文中setupProxy.js添加:/mynew

const context =  [
    "/weatherforecast",
    "/mynew",
];

module.exports = function(app) {
  const appProxy = createProxyMiddleware(context, {
    target: target,
    secure: false,
    headers: {
      Connection: 'Keep-Alive'
    }
  });

  app.use(appProxy);
};
Run Code Online (Sandbox Code Playgroud)

否则,框架会将 url 解释/mynew为屏幕的路由并按此处理。